LINQ到实体未返回预期结果 [英] LINQ to Entities not returning expected result

查看:89
本文介绍了LINQ到实体未返回预期结果的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用视图返回复杂的搜索查询.当我使用linq来查询EF时,它会返回同一行3次(实际的行数是正确的).

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).

使用LinqPad我已经对我的ef实体和实际的数据库视图运行了相同的linq.

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();

这是我同时使用的linq.

That is the linq I am using for both.

linqpad将lambda显示为: EF:

linqpad shows the lambda as this: EF:

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

数据库

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

我无法发布结果...但是EF返回同一记录的三行. DB返回3行的单个记录.就像我的sql查询一样.

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.

我需要对其EF LINQ进行更改以使其正常工作吗?

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

如果在SQL资源管理器中运行,则EF Linq查询生成的sql代码实际上会返回正确的结果.

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

推荐答案

如果患者"实体没有主键或推断为主键的列在结果集中的多个记录中相同,则会发生这种情况. EF使用内部身份映射,这要求每个唯一标识的记录都必须重用实体的同一实例.因此,如果您从数据库中返回三个具有EF唯一标识的记录,则会返回三个相同实例的枚举,这些实例代表结果集中的第一条记录(有关身份映射的更多信息,请参见

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.

这篇关于LINQ到实体未返回预期结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆