使用AdventureWorks数据库并发出此查询时:
AdventureWorksEntities entities = new AdventureWorksEntities(); entities.Contacts.Where(x => x.FirstName == "A" || x.FirstName == "B" || x.FirstName == "C") .ToList();
将被翻译成这个sql,它是最好的:
//ommited for brevity FROM [Person].[Contact] AS [Extent1] WHERE [Extent1].[FirstName] IN (N'A',N'B',N'C')
但是,当我发出此查询时:
entities.Employee.Where(x => x.Contact.FirstName == "A" || x.Contact.FirstName == "B" || x.Contact.FirstName == "C") .ToList();
我得到这个sql:
//ommited for brevity FROM [HumanResources].[Employee] AS [Extent1] INNER JOIN [Person].[Contact] AS [Extent2] ON [Extent1].[ContactID] = [Extent2].[ContactID] LEFT OUTER JOIN [Person].[Contact] AS [Extent3] ON [Extent1].[ContactID] = [Extent3].[ContactID] WHERE [Extent2].[FirstName] = N'A' OR [Extent3].[FirstName] IN (N'B',N'C')
为什么我会得到一个内部和外部联接,并且EF将两者分开?
注意使用包含创建相同的sql:
var names = new List<string>{"A","B","C"}; entities.Employee.Where(x => names.Contains(x.Contact.FirstName)).ToList();
编辑:所以它似乎是一个EF错误,我已经接受了提供解决方案的答案
编辑:打开连接问题,它位于here
解决方法
编写一个存储过程,接受TVP作为输入参数,让EF实现SP的结果:)