有人知道如何在 LINQ Lambda 上的外連接上轉換它嗎?
我想使用 lambda linq 來實作這一點
SELECT * FROM Posts as A LEFT JOIN Reactions as B on A.Id = B.PostId AND @userId = b.userid
這是我當前的 linq 代碼
return await _dbContext.Posts
.GroupJoin(_dbContext.Reactions,
post => post.Id, reaction => reaction.PostId,
(post, reactions) => new { post, reactions })
.SelectMany(x => x.reactions.DefaultIfEmpty(),
(post, reaction) => new { post.post, reaction })
uj5u.com熱心網友回復:
您想要完成的事情可以在 SQL 中以兩種不同的方式完成,并且可以將這些方式轉換為 Linq。
根據您的場景(資料量、索引等),您可能需要一個或另一個
選項 A:加入過濾后的資料
SELECT a.Name, b.*
FROM
tableA
LEFT JOIN tableB on
b.Action='delete' AND a.Id = b.Id
將在 LINQ 中翻譯為類似于:
var query =
from a in db.TableA
join pet in db.TableB.Where(x => x.Action=="delete") on a equals b.TableA into gj
from leftJoined in gj.DefaultIfEmpty()
并使用方法語法:
var query = tableA
.GroupJoin(
tableB.Where(x => x.Action == "delete"),
tableA => tableA,
tableB => tableB.tableA,
(tableA, tableBs) => new {tableA, tableBs}
).SelectMany(x => x.tableBs.DefaultIfEmpty())
選項 B:進行聯接,然后過濾資料
SELECT a.Name, b.*
FROM
tableA
LEFT JOIN tableB on a.Id = b.Id
WHERE
b.Id = NULL OR b.Action='delete'
將被翻譯為:
var query =
from a in db.TableA
join pet in db.TableB on a equals b.TableA into gj
from leftJoined in gj.DefaultIfEmpty()
where lefjoined == null || leftjoined.Action == "delete"
uj5u.com熱心網友回復:
左外連接是回傳第一個集合的每個元素的連接,無論它在第二個集合中是否有任何相關元素。DefaultIfEmpty您可以使用 LINQ 通過在組連接的結果上呼叫方法來執行左外連接。
您可以使用這種方法
查詢語法:
var query = (from post in Posts
join reaction in Reactions
on post.Id equals reaction.PostId
into reaction
from reaction in reaction.DefaultIfEmpty()
select new
{
post.Id,
//prod.Foo1,
//post.Foo2,
//reaction.Foo3,
//reaction.Foo4,
//you can select other fields too
}).OrderBy(ps => ps.Id);
有關更多資訊,請訪問執行左外連接
uj5u.com熱心網友回復:
通常你不會。在 LINQ 中根本不需要像這樣扁平化相關資料。只需獲取具有自然形狀的資料:
_dbContext.Posts.Include(p => p.Reactions)
這將回傳帖子和任何反應,而不必為每個反應重復帖子資料,或者對于沒有反應的帖子有空值。
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/463217.html
上一篇:c#中字串陣列的最大值和最小值
