开发者

Linq to Sql IsNull replacing NULL FK with existing FK

开发者 https://www.devze.com 2023-02-26 04:28 出处:网络
I need to transform an sql query to a Linq to SQL query, and i could\'nt get the result what i expect:

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))).DefaultIfEmpt开发者_运维百科y

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?


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]
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号