LINQ to Entities not returning expected result

风格不统一 提交于 2019-12-18 09:13:17

问题


I am using a view to return a complex search query. When I usin linq to query against EF it is returning the same row 3 times(the actual rowcount is correct).

using LinqPad I have run the same linq against my ef entity and the actual database view.

ReadmitPatientList
    .AsQueryable()
    .Where("PatientLastName.StartsWith(\"cooper\")")
    .OrderBy (rpl => rpl.PatientLastName)
    .Dump();

That is the linq I am using for both.

linqpad shows the lambda as this: EF:

ReadmitPatientList.MergeAs (AppendOnly)
   .Where ( => .PatientLastName.StartsWith ("cooper"))
   .OrderBy (rpl => rpl.PatientLastName)

DB

ReadmitPatientList
   .Where ( => .PatientLastName.StartsWith ("cooper"))
   .OrderBy (rpl => rpl.PatientLastName)

I cannot post the results...but EF returns three rows of the same record. DB returns 3 rows of individual records. As does my sql query.

What about my EF LINQ do I need to change to make it work correctly?


The sql code that is generated by the EF Linq query Actually returns the correct results if run in SQL explorer.


回答1:


This happens if Patient entity doesn't have primary key or columns inferred as primary key are same across multiple records in the result set. EF uses internally identity map which requires that each uniquely identified record must reuse the same instance of the entity. So if you return three records from the database which have same unique identification for EF will return enumeration of three same instances representing the first record from the result set (more about identity map also here). The same behaviour is in Linq-to-sql's DataContext.



来源:https://stackoverflow.com/questions/6077403/linq-to-entities-not-returning-expected-result

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!