[英]Entity Framework Core - How to correctly map relationships with composite key?
I have the following table structure 我有以下表格结构
Facility 设施
Id int (PK)
Name
Visit 访问
FacilityId int
Hour int
Value
Table Visit
has the composite key (FacilityId, Hour)
表
Visit
具有组合键(FacilityId, Hour)
The entity classes are defined as 实体类定义为
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; }
}
My DbContext
class has the following in OnModelCreating
method: 我的
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);
Here is the resulting JSON from my ASP.Net Core WebAPI 这是我的ASP.Net Core WebAPI生成的JSON
[{"id":1,"name":"Facility1","visits":null}, {"id":2,"name":"Facility2","visits":null}]
Question: why is the visits JSON null? 问题:为什么访问JSON为null? What configuration am I missing?
我缺少什么配置?
Thanks in advance. 提前致谢。
The EF have by default turned on Lazy Loading it's a reason why you get "visits":null
. EF默认情况下已启用“ 延迟加载”,这是您获得
"visits":null
。 But it's normal. 但这很正常。 Need to use Eager loading by using the
.Include()
function on your query. 需要通过在查询中使用
.Include()
函数来使用Eager加载。 See docs for specific examples usage eager loading. 请参阅docs,以获取特定示例用法的快速加载。
This sample code getall Facility
and Visits
此示例代码getall
Facility
和Visits
var allData = context.Facility
.Include(d => d.Visits)
.ToList();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.