[英]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.