我需要将sql查询转换为Linq to SQL查询,我无法得到我期望的结果: 我有2个表,Base,M表
BaseOne
{
MID (FK) , points to M
MChildID(FK, Nullable), points to M
}
M {
ID(PK)
}
简化选择:
SELECT * from BaseOne as f
LEFT JOIN M as m ON ISNULL(f.MChildID, f.MID) = m.ID
我试过了:
from f in BaseOne
from m in M.Where(function(x) If(f.MChildID.HasValue,x.ID.Equals(f.MChildID.Value),x.ID.Equals(f.MID.Value))).DefaultIfEmpty
它生成了这个SQL:
...
(CASE
WHEN [t0].[MID] IS NOT NULL THEN
(CASE
WHEN [t1].[ID] = ([t0].[MID]) THEN 1
WHEN NOT ([t1].[ID] = ([t0].[MID])) THEN 0
ELSE NULL
END)
ELSE
(CASE
WHEN [t1].[ID] = ([t0].[MChildID]) THEN 1
WHEN NOT ([t1].[ID] = ([t0].[MChildID])) THEN 0
ELSE NULL
END)
END)) = 1
LEFT OUTER JOIN ...
我跟着these instructions但这个例子并不是我尝试做的事情 有什么建议吗?
答案 0 :(得分:2)
您是否尝试过VB的二进制if() operator ?
from baseOne in BaseOne _
join m in M on if(baseOne.MChildID,baseOne.MID) equals m.ID _
select baseOne,m
它产生 COALESCE ,类似于ISNULL。
FROM [BaseOne] AS [t0]
INNER JOIN [M] AS [t1] ON (COALESCE([t0].[MChildID],[t0].[MID])) = [t1].[ID]