Monday, September 9, 2013

C# LINQ Query on SQL-Server View using Entity Framework 5 returns duplicate rows because of non-unique values in records first colum

In my C# VS2012 Project I'm using EF5 to query an SQL Server 2008 R2 database. Today we run into the strange issue that a query on a view  returned the expected number of rows, but the data contained many duplicate records. Running the created SQL-query in Management Studio, the results were fine.

How-I-fixed-it:
I found the right hints here: http://stackoverflow.com/questions/3977920/entity-framework-view-return-duplicate-records
and here:
http://jepsonsblog.blogspot.in/2011/11/enitity-framework-duplicate-rows-in.html?showComment=1348809764880#c1389404724781617559

The Problem was, that the FIRST column of my view was not a unique key, which seems to confuse EF.

Running the query in Management Studio returned:

Col1,Col2,Col3
1,0,1
1,1,1
1,2,1
2,0,7

In my code the result list of records was:
Col1,Col2,Col3
1,0,1
1,0,1
1,0,1
2,0,7

According to http://stackoverflow.com/questions/3977920/entity-framework-view-return-duplicate-records it's important, that the first colum of the query result contains a unique key:

When including a view in your Entity Model, the model seems to simply use the first not-nullable columns as primary key (as all columns used in the primary key should be non-nullable).

The suggestion how to fix it is to use the ROW_NUMBER () OVER () SQL to create an additional FIRST column in you view which has unique keys. Then update the model in Visual Studio.

No comments:

Post a Comment