Linq - left join on multiple conditions

如何使用Linq将表“T_DIM_NETWORK”和表“T_IDAU_DIAGNOSIS”左联(左联条件是“StructId”、“DtuId”、“Subnet”和“NodeId”均相等)?

var queryDiag = from n in entity.T_DIM_NETWORK
    join d in entity.T_IDAU_DIAGNOSIS on
        new {structId = n.StructId, dtuId = n.DtuId, subnet = n.Subnet, nodeId = (int?) n.NodeId} equals
        new {structId = d.StructId, dtuId = d.DtuId, subnet = d.Subnet, nodeId = d.NodeId} into nd
    from id in nd.DefaultIfEmpty()
    where n.StructId == structId
        && n.DtuId == dtuId
        && n.Enable
    select new
    {
        networkId = n.ID,
        nodeId = n.NodeId,
        di = n.DI, // 采集周期, 粒度
        diu = n.DIU, // 采集周期单位, 粒度单位
        wakeDelay = n.WakeDelay,
        diagName = id.T_DIM_IDAU_DIAGNOSIS_ATTRIBUTES.name,
        diagResult = id.DiagResult,
        diagTime = id.DiagTime
    };

 说明:

表“T_DIM_NETWORK”中“NodeId”类型为(int, not null),而“T_IDAU_DIAGNOSIS”表中“NodeId”类型为(int, null), 所以,为了对齐数据类型,linq语句中“equals”左侧的“n.NodeId”前面需要加上“(int?)”可空类型转换。否则,会出现如下 编译错误信息:

The type arguments cannot be inferred from the query.  (从查询中无法推断类型参数)

错误原因:

You are getting this error because the types on either side of the "equals" clause do not match.  即,"equals"两边的数据类型并不匹配导致了错误!

 

【小结】

LINQ下使用“ join on”多条件比对产生“LEFT JOIN”功能时, equals两边的参数字段名的大小写及数据类型必须完全匹配, 否则会导致“The type arguments cannot be inferred from the query.”编译错误。

  

附: from a from b 左联语法 

from a in tablea
from b in tableb
.Where( wb => ( a.col1 == wb.col1 || a.col2 == wb.col2)) // (parameter) tableb wb
.DefaultIfEmpty()
select new { col1 = a.col1, col2 = a.col2 }

   

【引用】https://social.msdn.microsoft.com/Forums/zh-CN/e09b50af-5ab4-4cfb-9617-ef2be339c17f/join-on-multiple-conditions?forum=linqprojectgeneral

           http://stackoverflow.com/questions/1264993/linq-left-join-on-multiple-or-conditions

 

你可能感兴趣的:(Linq - left join on multiple conditions)