EF Core中的多对多关系映射

时间:2018-01-24 20:11:21

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

我在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

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

我希望我解释得太复杂。

1 个答案:

答案 0 :(得分:3)

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

var foods = await context.Foods
    .Include(f => f.MealFoods)
        .ThenInclude(mf => mf.Meal) // <--
    .ToListAsync();

struct Lazy {
       let id: String
       lazy var greeting: String = { "hello" }()
}