[英]How to load many-to-many object graphs using Entity Framework?
我有一個多對多關系(在此示例中為“左”,“右”和“ JoJoin”),還有另一個實體“衛星”,可以鍵入“左”。 碰巧的是,Sattelite的FK也具有唯一的索引。 我的目標是使用Satellite的where子句的屬性加載一個Joinder實體及其左和右實體。
我已經嘗試了多種方法,但是我對Linq的詞匯很薄,甚至我都不知道我要尋找的術語。
var joinder = dbContext.Joinders
.Include(j => j.Left)
.Include(j => j.Right)
.Include(j => j.Left.Satellites)
.FirstOrDefault(s => s.Name == "Hubble");
這不起作用,因為FirstOrDefault子句沒有用於分析名稱的s上下文。
var joinder = dbContext.Joinders
.Include(j => j.Left)
.Include(j => j.Right)
.Include(j => j.Left.Satellites)
.Select(j => j.Left.Satellites)
.Where(s => s.Name == "Hubble");
這不起作用,因為從Select出來的類型是IQueryable<Collection<Satellite>>
,這令人困惑。
var query = from j in dbContext.Joinders
join l in dbContext.Lefts on j.LeftId equals l.Id
join r in dbContext.Rights on j.RightId equals r.Id
join s in dbContext.Satellites on l.Id equals s.LeftId
where s.Name == "Hubble"
select j;
該查詢會編譯並運行,但會向我返回完全脫水的對象-我返回的Joinder引用具有Left和Right屬性均為null。
var query = from j in dbContext.Joinders
join l in dbContext.Lefts on j.LeftId equals l.Id
join r in dbContext.Rights on j.RightId equals r.Id
join s in dbContext.Satellites on l.Id equals s.LeftId
where s.Name == "Hubble"
select new Joinder
{
Left = l,
Right = r,
Left.Satellites = ...?
};
這似乎不起作用,因為我似乎無法在自動初始化程序中取消引用這些屬性名稱。
有人知道怎么做嗎? 本質上,我想搜索“多對多實體框架”,但我想並不是每個人都會像我這樣說。
var joinder = dbContext.Joinders
.Include(j => j.Right)
.Include(j => j.Left.Satellites)
.FirstOrDefault(j => j.Left.Satellites.Any(s => s.Name == "Hubble"));
它返回第一個聯接,該聯接具有至少一個具有給定名稱的衛星。 .Include(j => j.Left.Satellites)
也將包括Left
實體(到最后一個屬性的路徑上的所有東西),因此不需要單獨的Include(j => j.Left)
。
編輯
如果你不希望加載相關的Satellites
與一起Joinder
,只需更換.Include(j => j.Left.Satellites)
由.Include(j => j.Left)
FirstOrDefault
的謂詞(取決於Satellite
屬性)仍將起作用。
嘗試這個
var joinders = dbContext.Joinders
.Include(j => j.Left)
.Include(j => j.Right)
.Include(j => j.Left.Satellites)
.Where(j => j.Left.Satellites.Any(s => s.Name == "Hubble");
這將返回“所有聯接”,其中鏈接到“左”的任何衛星的名稱為“哈勃”。 我知道“左”和“右”會急於加載,但對於衛星,我不確定。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.