0

我有很多一對多的使用關係表導致這些關係的父母和孩子的關係並不在EF核心自動尚不支持:包括泛型列表屬性的實體在ASP.NET的EntityFramework核心

class Parent{ 
    [Key] 
    public int Id{get;set;} 
    public List<ParentChild> ParentChilds{get;set;} 
} 

class Child{ 
    [Key] 
    public int Id{get;set;} 
    public List<ParentChild> ParentChilds{get;set;} 
} 

class ParentChild{ 
    public int ParentId{get;set;} 
    public Parent Parent{get;set;} 
    public int ChildId{get;set;} 
    public Child Child{get;set;} 
} 

爲了編輯父母,我需要得到他所有的孩子。似乎是Include()

var db = new MyDbContext(); 
var parentWithChilds = db.Parents.Include(p => p.ParentChilds) 
    .FirstOrDefault(p => p.Id == 1); 

這給了我的ParentChild istances列表中的任務。但ParentChildChild實體沒有自動加載,所以我只有孩子的Id,但沒有我需要的Child對象本身。我發現ThenInclude這似乎被設計用於這樣的情況下,並從實施例等this我做了以下:

var parentWithChilds = db.Parents.Include(p => p.ParentChilds) 
    .ThenInclude(p => p.Select(x => x.Child)) 
    .FirstOrDefault(p => p.Id == 1); 

但它拋出異常:

屬性表達式「P => {從父子x in p select [x] .Child => FirstOrDefault()}'無效。表達式應該表示一個屬性訪問:'t => t.MyProperty'。

那麼如何做到這一點呢?我想避免像手動獲取實體這樣不必要的查詢:

user.ParentChilds.ForEach(pc => pc.Child = db.Childs.FirstOrDefault(x => x.Id == pc.ChildId)); 

回答

2

好像我誤解了ThenInclude使用,因爲它是指子實體。有其可能的一個列表來定義實體也加載在列表如下:

var parentWithChilds = db.Parents.Include(p => p.ParentChilds) 
    .ThenInclude(p => p.Child) 
    .FirstOrDefault(p => p.Id == 1); 

Visual Studio中具有顯示在智能感知那些超載的問題,但它的存在並不會導致錯誤。

+3

'.ThenInclude'有兩個重載(當遵循集合導航屬性時)。一個用於'TPreviousProperty',另一個用於'ICollection '。對於一些人來說,Visual Studio似乎總是爲「TPreviousProperty」變體顯示intellisense,並且只顯示集合擴展方法而不是模型。但是,如果在沒有自動完成的情況下鍵入屬性名稱,那麼它將選擇正確的屬性名稱(就像你使用'.ThenInclude(p => p.Child)'所做的那樣)並且不會顯示編譯器錯誤 – Tseng

+0

是的,這是問題所在, t首先注意到過載,因爲它在智能感知中缺失。 – Lion

相關問題