d51*_*512 2 sql entity-framework join
我有一个 SQL 查询,我试图将其转换为实体框架表达式。连接子句之一对 null 进行了测试,我不确定如何在 EF 中表达它。这是 SQL 查询,注意联接实际上有多个条件:
SELECT T1.*
FROM product T1
INNER JOIN T2 ON T1.pk1 = T2.fk1
INNER JOIN T3 ON T2.pk2 = T3.fk2 AND T3.x IS NULL <-- this is the issue
Run Code Online (Sandbox Code Playgroud)
出于对简单事情的盲目希望,我尝试了这个 EF 表达式:
from t1 in ctx.T1
join t2 in ctx.T2 on t1.pk1 equals t2.fk1
join t3 in ctx.T3 on t2.pk2 equals t3.fk2 && t3.x == null
select t1
Run Code Online (Sandbox Code Playgroud)
编译器不喜欢这&& t3.x == null部分。它说
错误 CS0019 运算符“&&”不能应用于“int”和“bool”类型的操作数
所以我尝试了这个(注意 T3.x 是一个可为空的日期字段):
from t1 in ctx.T1
join t2 in ctx.T2 on t1.pk1 equals t2.fk1
join t3 in ctx.T3 on new { A = t2.pk2, B = null as DateTime? } equals new { A = t3.fk2 && B = t3.x }
select t1
Run Code Online (Sandbox Code Playgroud)
它编译,但是当我运行它时,我得到
无法创建类型为“System.Object”的空常量值。在此上下文中仅支持实体类型、枚举类型或基本类型。
那么我该怎么做呢?
更新:正如 Ivan Stoev 指出的那样,问题是我使用的是null as DateTime?而不是(DateTime?)null. 所以工作查询看起来像这样:
from t1 in ctx.T1
join t2 in ctx.T2 on t1.pk1 equals t2.fk1
join t3 in ctx.T3 on new { A = t2.pk2, B = (DateTime?)null } equals new { A = t3.fk2 && B = t3.x }
select t1
Run Code Online (Sandbox Code Playgroud)
要么将条件移动到where子句(对于内部连接,它真的无关紧要):
join t3 in ctx.T3 on t2.pk2 equals t3.fk2
where t3.x == null
Run Code Online (Sandbox Code Playgroud)
或使用以下
join t3 in ctx.T3
on new { A = t2.pk2, B = (DateTime?)null }
equals new { A = t3.fk2, B = t3.x }
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1338 次 |
| 最近记录: |