Sunday, September 23, 2012

Why Linq to Entity select on view returns a repeat of first record?


The 'sql' query and ‘Linq to sql’ are working fine. But ‘Linq to Entity'  Select on view return a repeat
of the first record.
Reason :
The difference in behavior between LINQ-to-SQL and LINQ-to-Entities is in the underlying mapping strategies of the technologies. LINQ-to-SQL only supports 1:1 mapping with the database objects. Entity Framework supports multiple entity associations in the conceptual model, and entities are not restricted to a 1:1 mapping with the underlying data objects.

This problem has occurred for me when the view entity does not have a clear primary key which EF wants. If you look at your edmx after adding the view entity to the designer you will probably notice that there are several columns (incorrectly) chosen by EF as the surrogate key.

If you have a primary/surrogate unique key make sure those column(s) are the only ones selected as the view’s key.

Otherwise, if no such key exists, add a uniqueidentifer column to your view using newid() function. Delete and add the view back to your edmx designer. Then on the designer, unselect all the other columns chosen as the key and select the pseudo column added to the view as the unique key.

One annoying thing is that any time you change the view and re-add the view entity back to the designer you likely will have to re-select the proper key.

No comments: