實體框架核心 - 如何正確映射與復合鍵的關係?

c# entity-framework-core json

我有以下表格結構

設施

Id int (PK)
Name 

訪問

FacilityId int 
Hour int
Value

Visit具有復合鍵(FacilityId, Hour)

實體類定義為

class Facility
{
    public int Id { get; set; }
    public string Name { get; set; }   
    public ICollection<Visit> Visits { }
}

class Visit
{
    public int FacilityId { get; set; }
    public int Hour { get; set; }
    public int Value { get; set; }
    public Facility Facility { get; set; }
}

我的DbContext類在OnModelCreating方法中具有以下內容:

modelBuilder.Entity<Facility>()
                .ToTable("Facility")
                .HasKey(f => f.Id);
modelBuilder.Entity<Facility>()
                .HasMany(f => f.Visits)

modelBuilder.Entity<Visit>()
                .ToTable("Visits")
                .HasKey(v => new { v.FacilityId, v.Hour});
modelBuilder.Entity<Visit>()
                .HasOne(a => a.Facility)
                .WithMany(a => a.Visits)
                .HasForeignKey(a => a.FacilityId)
                .HasPrincipalKey(a => a.Id); 

這是我的ASP.Net Core WebAPI生成的JSON

[{"id":1,"name":"Facility1","visits":null},      {"id":2,"name":"Facility2","visits":null}]

問題:為什麼訪問JSON為空?我錯過了什麼配置?

提前致謝。

一般承認的答案

EF默認情況下打開了Lazy Loading,這就是你獲得"visits":null的原因"visits":null 。但這很正常。需要在查詢中使用.Include()函數來使用Eager加載。有關使用急切加載的具體示例,請參閱文檔

此示例代碼getall FacilityVisits

 var allData =  context.Facility
               .Include(d => d.Visits)
               .ToList();


Related

許可下: CC-BY-SA with attribution
不隸屬於 Stack Overflow
許可下: CC-BY-SA with attribution
不隸屬於 Stack Overflow