如何在使用LINQ加入可空属性时阻止Entity Framework添加ISNULL检查

时间:2017-04-19 14:51:11

标签: c# entity-framework linq

我有一个连接2个可空属性的Linq查询。

 var result = (from A in context.TableA
             join B in context.TableB
             on A.ExecutionId equals B.ExecutionId
             where B.InsertedBy == userName 

rep.ExecutionId和sch.ExecutionId在数据库中都是可空的int。我真正希望实体框架生成的是

select 
column1     
from TableA A
inner join TableB B on A.ExecutionId = B.ExecutionId
where B.InsertedBy = @username

但我得到的是

select 
column1
from TableA A
inner join TableB B on A.ExecutionId = B.ExecutionId 
OR ((A.[ExecutionId] IS NULL) AND (B.[ExecutionId] IS NULL))
where B.InsertedBy = @username

(ExecutionIds中的任何一个都不是主键)。第二个查询给了我比我需要的记录更多的记录,但更重要的是,不是我想要的查询。如何编写LINQ以便它生成第一个查询或等效的?

1 个答案:

答案 0 :(得分:1)

如果您不想要ExecutionIDnull的任何记录,请使用过滤器

var result = (from A in context.TableA.Where( a => a.ExecutionID != null )
              join B in context.TableB.Where( b => b.ExecutionId != null ) 
              on A.ExecutionId equals B.ExecutionId
              where B.InsertedBy == userName 
              ...`enter code here`