var query = from k in DBContext.KCYD join i in DBContext.ITEM on k.SPXXID equals i.ITEM_ID into g from gc in g.DefaultIfEmpty() join s in DBContext.SPKC on k.SpxxId equals s.SPXXID into g1 from gc1 in g1.DefaultIfEmpty() where k.Ckid == gc1.CKID select new { ... ... };
但是生成的SQL语句,KCYD和ITEM表是LEFT OUTER JOIN的,但是联SPKC表却变成了INNER JOIN,这是为啥呢,经过一番折腾下来,发现问题出在where k.Ckid == gc1.CKID,如果把这个条件去掉的话,那就成了LEFT OUTER JOIN了,然后我就在想这个条件应该放在哪呢,LINQ里面到底支不支持联合主键的问题呢,在网上搜了半天,发现可以用 on new {字段1,字段2} equals new {字段1,字段2} into g的方法,于是修改代码如下:
var query = from k in DBContext.KCYD join i in DBContext.ITEM on k.SPXXID equals i.ITEM_ID into g from gc in g.DefaultIfEmpty() join s in DBContext.SPKC on new {k.SpxxId,k.Ckid} equals new {s.SPXXID,s.CKID} into g1 from gc1 in g1.DefaultIfEmpty() select new { ... ... };
但是很不给力的是这样居然提示错误:The type arguments cannot be inferred from the query. 简直就是杯具,难道LINQ不支持这样搞?唉,在我绝望的时候同事为我看出了端倪,原来equals两边的参数字段名的大小写必须完全匹配。即完整代码如下:
var query = from k in DBContext.KCYD join i in DBContext.ITEM on k.SPXXID equals i.ITEM_ID into g from gc in g.DefaultIfEmpty() join s in DBContext.SPKC on new {SPXXID=k.SpxxId,CKID=k.Ckid} equals new {s.SPXXID,s.CKID} into g1 from gc1 in g1.DefaultIfEmpty() select new { ... ... };