如何在join linq语法中比较null

um6iljoc  于 2023-05-26  发布在  其他
关注(0)|答案(5)|浏览(166)

使用EF4C #,面对连接中的问题. sql语法

Select a.Code, b.Name from DepartmentMaster a
Join DepartmentDetail  b on isnull( a.ID,0) =isnull( b.ID,0)

**注意:**a.ID,B.ID都可以为空

我想把上面的语法转换成Linq的语法,但Bellow的语法对我不起作用

Var r=from a in DepartmentMaster
Join b in DepartmentDetail  on a.ID equals b.ID
Select a.Code,b.Name

需要帮助在linq ef中编写sql语法isnull()可比进程。
如有任何疑问,请询问。

4sup72z8

4sup72z81#

如果id为null,可以使用null-coalescing运算符提供默认值:

from c in DepartmentMaster
join b in DepartmentDetail
    on (a.ID ?? 0) equals (b.ID ?? 0)
select new {
    a.Code, b.Name
}

这将生成查询

SELECT [t0].[Code], [t1].[Name] AS [ID1]
FROM [DepartmentMaster] AS [t0]
INNER JOIN [DepartmentDetail] AS [t1] 
    ON (COALESCE([t0].[ID],@p0)) = (COALESCE([t1].[ID],@p1))

这与ISNULL不完全相同,但结果应该相同。

lyr7nygr

lyr7nygr2#

这可能对你有帮助

Var r=from a in DepartmentMaster
Join b in DepartmentDetail  on a.(x => (int?)a.ID) ?? 0 equals b.(y => (int?)b.ID) ?? 0
Select a.Code,b.Name
aelbi1ox

aelbi1ox3#

您可以使用DefaultIfEmpty,它将空集合替换为一个默认值的集合。因为int的默认值是0

var r=from a in DepartmentMaster
join b in DepartmentDetail  on a.ID.DefaultIfEmpty() equals b.ID.DefaultIfEmpty()
Select a.Code,b.Name
dgenwo3n

dgenwo3n4#

你应该能够做这样的事情:

Join b in DepartmentDetail  on (a.ID == null ? 0 : a.ID) equals (b.ID == null ? 0 : b.ID)
bfhwhh0e

bfhwhh0e5#

我做了一些测试,发现在.NET 6.0与Microsoft.EntityFrameworkCore 6上,当我们比较可空字符串时,两者之间有很大的区别:

var queriableResult = from valueCount in queriableValueCount
join valueIds in queriableValueIds
on valueCount.Value equals valueIds.Value
select new { ... }

这将给予以下ON子句:

ON [t].[Value] = [t0].[Value]

var queriableResult = from valueCount in queriableValueCount
join valueIds in queriableValueIds
on new { valueCount.Value } equals new { valueIds.Value }
select new { ... }

这将给予所需的ON子句:

ON ([t].[Value] = [t0].[Value]) OR (([t].[Value] IS NULL) AND ([t0].[Value] IS NULL))

相关问题