【问题标题】:Many to many relationship mapping in EF CoreEF Core 中的多对多关系映射
【发布时间】:2018-07-03 23:46:50
【问题描述】:

我在 EF 核心中存在多对多关系的问题。 我有以下模型类:

public class Meal
{
    public int Id { get; set; }
    [Required]
    public int Insulin { get; set; }
    public MealType Type { get; set; }

    public ICollection<MealFood> MealFoods { get; set; }

    public Meal()
    {
        MealFoods = new Collection<MealFood>();
    }
}

public class Food
{
    public int Id { get; set; }
    [StringLength(255)]
    public string Name { get; set; }
    [Required]
    public int Carbohydrates { get; set; }
    public ICollection<MealFood> MealFoods { get; set; }

    public Food()
    {
        MealFoods = new Collection<MealFood>();
    }
}

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<FoodResource> Foods { get; set; }

    public MealResource()
    {
        Foods = new Collection<FoodResource>();
    }
}

我已经在我的 DbContext 中完成了映射:

protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder.Entity<MealFood>().HasKey(mf => new { mf.MealId, mf.FoodId });
        modelBuilder.Entity<MealFood>().HasOne(mf => mf.Meal).WithMany(m => m.MealFoods).HasForeignKey(mf => mf.MealId);
        modelBuilder.Entity<MealFood>().HasOne(mf => mf.Food).WithMany(f => f.MealFoods).HasForeignKey(mf => mf.FoodId);
    }

这个电话有问题:

var meals = await context.Meals.Include(m => m.MealFoods).ToListAsync();

This returns almost everything I need, except the navigation properties from MealFoods

之所以想要这些属性,是因为我想做如下映射:

CreateMap<Meal, MealResource>().ForMember(mr => mr.Foods, opt => opt.MapFrom(x => x.MealFoods.Select(y => y.Food).ToList()));

我已经找到了这个: Automapper many to many mapping

但是(也许我没有得到什么)这不起作用,因为 MealFood 中名为 Food 的属性为空。

希望我没有解释太复杂。

【问题讨论】:

    标签: c# .net-core many-to-many entity-framework-core


    【解决方案1】:

    当您包含导航属性时,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();
    

    【讨论】:

    • 是的!这是一个,它有效!非常感谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-05-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多