2016-09-14 95 views
0

在我的ASP.NET Core Web API應用程序中,我在實體框架核心中遇到與實體相關的問題。當我通過Postman向控制器發送GET請求時,所有Model的記錄都會返回,但其相關實體的導航屬性會返回爲空。不幸的是,也沒有發生錯誤或異常。 (簡化)代碼如下:未定義實體關係

//DBContext 
protected override void OnModelCreating(ModelBuilder modelBuilder) 
    { 

     modelBuilder.Entity<Location>(); 

     modelBuilder.Entity<Person>(entity => 
     { 
      entity.HasOne(p => p.Location) 
       .WithMany(l => l.People) 
       .HasForeignKey(p => p.Location_ID); 
     }); 
    } 


//Person Model 
public partial class Person 
{ 
    [Key] 
    public int People_ID { get; set; } 

    public int? Location_ID { get; set; } 
    public Location Location { get; set; } 
} 

//Location Model 
public partial class Location 
{ 
    public Location() 
    { 
     People = new HashSet<Person>(); 
    } 

    [Key] 
    public int Location_ID { get; set; } 

    public ICollection<Person> People { get; set; } 
} 

據我所知,因爲我所規定的兩個模型利用在OnModelCreating方法的流利API相關,這些屬性應該是「即時加載」。爲什麼這不會發生?

回答

1

據我瞭解,因爲我決定這兩種型號都使用在OnModelCreating方法流利API相關的,屬性應該是「即時加載」

你理解錯了。 Eager Loading行爲不是隱式的(如延遲加載),您必須使用Include/ThenInclude方法明確請求它。

例如,以下將返回Person實體Location屬性填充:

return db.Set<Person>().Include(p => p.Location); 
+0

在什麼水平將這個return語句聲明的? –

+0

根據我的數據庫首先EF生成的模型,我有DbSets聲明在我的DbContext文件的底部。然後,我將DbContext擴展到一個'method repository'類,它通過DbContext加載的屬性顯式調用DbSets,例如'return _db.People;' –

+0

'_db.Set ()'與'_db.People'相同。你在哪裏以及如何實現急切的加載超出了你當前問題的範圍,我相信這個問題的答案是覆蓋範圍。 –