如何将此Linq查询更改为左连接而不是内连接?
from EH in db.EventsHistory
join AH in db.EventsAttr on EH.TRANSACTIONID equals AH.TRANSACTIONID
join E in db.Events on EH.EVTID equals E.EVTID
group EH by new { EH.TRANSACTIONID, EH.MACGRP, EH.MACID, EH.ORDID, EH.ORDSPLIT, EH.LINID, EH.EVTDATETIME, EH.MATID, EH.PRODID, E.DESC, NUM_ATTR = AH.TRANSACTIONID } into grouped
select new { grouped.Key.TRANSACTIONID, grouped.Key.MACGRP, grouped.Key.MACID, grouped.Key.ORDID, grouped.Key.ORDSPLIT, grouped.Key.LINID, grouped.Key.EVTDATETIME, grouped.Key.MATID, grouped.Key.PRODID, grouped.Key.DESC, NUM_ATTR = grouped.Count() };
答案 0 :(得分:0)
在Linq中LEFT JOIN是通过使用方法DefaultIfEmpty
的组连接创建的。基本结构使用查询语法如下所示:
var query = from c in db.Customers
join o in db.Orders on c.Id equals o.CustomerId into g
from o in g.DefaultIfEmpty()
select new
{
Customer = c,
Order = o
};
方法语法示例:
var query = db.Customers
.GroupJoin(db.Orders, c => c.Id, o => o.CustomerId, (c, og) => new
{
Customer = c,
Order = og.DefaultIfEmpty()
});
所以你的查询应该是这样的:
var query = from eh in db.EventsHistory
join ah in db.EventsAttr on eh.TransactionId equals ah.TransactionId into g
join e in db.Events on eh.EvtId equals e.EvtId into g2
from ah in g.DefaultIfEmpty()
from e in g2.DefaultIfEmpty()
group eh by new { ... } into grouped
select new { ... }