Repository Linq LeftJoin (GroupJoin + SelectMany) and Join
假設有兩個倉儲 A,B
要用A.bId去跟B.Id為依據
去拿B.Name欄位
最後合併 A.Id與B.Name
成為 cDto 作為資料傳輸物件輸出
- Left Join (GroupJoin + Select) 子集合選擇特定欄位
var joinQuery = order
.GroupJoin(orderStatus,
o => o.Id,
s => s.Id,
(o, s) => new {
o.Id,
data = s.Select(x => new {
x.Item,
x.Qty
}
)
}
)
.Where(x => x.data.Any())
.ToList();
- Left Join (GroupJoin + SelectMany) 攤平子集合
var joinQuery = _aRepository.GetAll()
.GroupJoin(_bRepository.GetAll(),
a => a.bId,
b => b.Id,
(a,b) => new{a,b})
.SelectMany(result => result.b.DefaultIfEmpty(),
(x, y) => new cDto{
Id = x.a.Id,
Name = y.Name ?? "N/A"
});
- Join (innerJoin)
var joinQuery = _aRepository.GetAll()
.Join(_bRepository.GetAll(),
a=>a.bId,
b=>b.Id,
(a,b)=>new cDto{
Id = a.Id,
Name = b.Name
});
B倉儲只要沒有A的bID,該筆資料就不會出現在結果