![](/img/trans.png)
[英]The link table in Many-to-many relationship is not populated by the Seed method in Code First Entity Framework
[英]Getting many-to-many objects populated with Entity Framework 7
这些由以下POCO类表示,首先使用Entity Framework代码从中创建数据库:
public class ExerciseCategory
{
public int ExerciseId { get; set; }
public Exercise Exercise { get; set; }
public int CategoryId { get; set; }
public Category Category { get; set; }
}
public class Exercise
{
public int Id { get; set; }
public string Name { get; set; }
public List<ExerciseCategory> ExerciseCategories { get; set; }
}
public class Category
{
public int Id { get; set; }
public string Name { get; set; }
public List<ExerciseCategory> ExerciseCategories { get; set; }
}
现在,我需要进行所有练习,其中包括它们所属的类别列表。 由于这是多对多关系,因此一个练习可以具有许多类别。 我尝试了以下代码:
_context.Exercises
.Include(e => e.ExerciseCategories)
.OrderBy(e => e.Name).ToList();
但是它不会填充ExerciseCategory的属性...
我应该如何构造查询以获取ExerciseCategory的Category属性? 最好在一个查询中而不是在“ for”循环中,因为可能在一页上显示很多练习,而性能可能是一个问题。
实体框架7多对多支持仍未完成。 当前,您必须为“ Exercise
和“ Category
实体手动映射一对多关系。 您的实体类别已正确设置。 现在,您需要在DbContext类中重写OnModelCreating
方法:
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<ExerciseCategory>()
.HasKey(t => new { t.ExerciseId, t.CategoryId });
modelBuilder.Entity<ExerciseCategory>()
.HasOne(pt => pt.Exercise)
.WithMany(p => p.ExerciseCategories)
.HasForeignKey(pt => pt.ExerciseId);
modelBuilder.Entity<ExerciseCategory>()
.HasOne(pt => pt.Category)
.WithMany(t => t.ExerciseCategories)
.HasForeignKey(pt => pt.CategoryId);
}
请参阅关系-实体框架7.0文档
还要确保在上下文中包含DbSet<ExerciseCategory>
属性。
之后,可以按以下方式构建完整的热切查询:
_context.ExerciseCategories.Include(ec => ec.Exercise)
.Include(ec => ec.Category)
.Select(ec => ec.Exercise)
或通过在Exercise-query上使用ThenInclude:
_context.Exercises.Include(e => e.ExerciseCategories)
.ThenInclude(ec => ec.Category)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.