Reputation: 355
I need to transform an sql query to a Linq to SQL query, and i could'nt get the result what i expect: I have 2 tables, Base, M tables
BaseOne
{
MID (FK) , points to M
MChildID(FK, Nullable), points to M
}
M {
ID(PK)
}
The Simplified select:
SELECT * from BaseOne as f
LEFT JOIN M as m ON ISNULL(f.MChildID, f.MID) = m.ID
I tried this:
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
It generated this 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 ...
I followed these instructions but this example is not exaclty what i try to do.
Any suggestions?
Upvotes: 2
Views: 409
Reputation: 4299
Have you tried VB's binary if() operator?
from baseOne in BaseOne _
join m in M on if(baseOne.MChildID,baseOne.MID) equals m.ID _
select baseOne,m
It produces a COALESCE, which is similar to ISNULL.
FROM [BaseOne] AS [t0]
INNER JOIN [M] AS [t1] ON (COALESCE([t0].[MChildID],[t0].[MID])) = [t1].[ID]
Upvotes: 2