- In this walkthrough we will learn How to fix the Entity Framework error "does not have a primary key defined and no valid primary key could be inferred".
- In the case you design an Entity Type in the Entity Framework's conceptual entity model, based not on a sql table, but on a sql view, or in the case your table does not have a primary key defined, the entity framework will try to infer which column can be the unique KEY of the entity.
You cannot state a primary key for an SQL SERVER view, so if you create an Entity Framework entity based on a view, you may have an issue here.
Usually the Entity Framework will succeed inferring the primary key: if the SQL view is the result of a JOIN and you bring some primary key between the selected columns of the view, it will take that field as the unique KEY of the entity.
The error "does not have a primary key defined and no valid primary key could be inferred" tells us that the Entity Framework couldn't infer the primary key.
- In our example, we see that the entity CRM_USER_ACTIVITIES, based on the view of the same name, does not have a primary key:
- We received the error message because there is not field at the view that the Entity Framework can recognize as an original Primary Key of some table.In our example, NEW_IDENTIFIER is not a key, and ACTIVITYID, although a primary key of the table LETTERBASE, is camouflaged here inside the "GUID" column:
- To solve the problem, let's wrap the entire select inside another select which will load the Primary Key of the LETTERBASE table we spoke of before, ACTIVITYID, using an INNER JOIN, so that the Entity Framework will recognize the key: therefore state BEFORE the query the code
- And at the end of the query , let's close the JOIN defining the ON clause using the primary key:
- Now save the view using ALTER and rerun the Entity Framework rebuilding the Visual Studio project:
- Just press at Finish after selecting the CRM_USER_ACTIVITIES from the "Views" tree item:
- Another approach to solve the problem, is to add a new column to the SQL SERVER view, called ID. This column will be unique, because we'll insert in it a DENSE_RANK over the field that we know is unique:
That's all...Enjoy Dynamics CRMכתב: כרמל שוורצמן
A Step-By-Step Walk-Through CRM 2011 designed for Begginer and Professional CRM Developers
Microsoft Dynamics CRM 2011
Thursday, October 3, 2013
Step-By-Step How to fix the Entity Framework error "no valid primary key could be inferred"
by Carmel Schvartzman
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment