EF Core中的多对多关系映射
我在EF核心中存在多对多关系的问题。 我有以下模型类:
public class Meal { public int Id { get; set; } [Required] public int Insulin { get; set; } public MealType Type { get; set; } public ICollection MealFoods { get; set; } public Meal() { MealFoods = new Collection(); } } public class Food { public int Id { get; set; } [StringLength(255)] public string Name { get; set; } [Required] public int Carbohydrates { get; set; } public ICollection MealFoods { get; set; } public Food() { MealFoods = new Collection(); } } public class MealFood { public int MealId { get; set; } public Meal Meal { get; set; } public int FoodId { get; set; } public Food Food { get; set; } }
我有以下API资源类:
public class MealResource { public int Id { get; set; } public int Insulin { get; set; } public MealType Type { get; set; } public ICollection Foods { get; set; } public MealResource() { Foods = new Collection(); } }
我在DbContext中完成了映射:
protected override void OnModelCreating(ModelBuilder modelBuilder) { modelBuilder.Entity().HasKey(mf => new { mf.MealId, mf.FoodId }); modelBuilder.Entity().HasOne(mf => mf.Meal).WithMany(m => m.MealFoods).HasForeignKey(mf => mf.MealId); modelBuilder.Entity().HasOne(mf => mf.Food).WithMany(f => f.MealFoods).HasForeignKey(mf => mf.FoodId); }
我有这个电话的问题:
var meals = await context.Meals.Include(m => m.MealFoods).ToListAsync();
除了MealFoods的导航属性外,这几乎可以返回我需要的所有内容
我之所以需要这些属性,是因为我想做以下映射:
CreateMap().ForMember(mr => mr.Foods, opt => opt.MapFrom(x => x.MealFoods.Select(y => y.Food).ToList()));
我已经发现了这一点: 自动映射多对多映射
但是(也许我没有得到什么)这不起作用,因为在MealFood中称为Food的属性为null。
我希望我没有解释太复杂。
当您包含导航属性时,EF Core会自动填充反向导航属性,例如包括Meal.MealFoods
将自动填充MealFood.Meal
,包括Food.MealFoods
将自动填充MealFood.Food
等。为了填充其他导航属性,您需要使用额外的ThenInclude
。 例如
var meals = await context.Meals .Include(m => m.MealFoods) .ThenInclude(mf => mf.Food) // <-- .ToListAsync();
要么
var foods = await context.Foods .Include(f => f.MealFoods) .ThenInclude(mf => mf.Meal) // <-- .ToListAsync();