Many to many relationship mapping in EF Core

后端 未结 1 1022
无人及你
无人及你 2020-12-02 01:18

I have a problem with many to many relationship in EF core. I have the following model classes:

public class Meal
{
    public int Id { get; set; }
    [Requ         


        
相关标签:
1条回答
  • 2020-12-02 02:00

    When you include navigation property, EF Core automatically fills the inverse navigation property, e.g. including Meal.MealFoods will automatically fill MealFood.Meal, including Food.MealFoods will automatically populate MealFood.Food etc. In order to populate other navigation properties you need to use additional ThenInclude. E.g.

    var meals = await context.Meals
        .Include(m => m.MealFoods)
            .ThenInclude(mf => mf.Food) // <--
        .ToListAsync();
    

    or

    var foods = await context.Foods
        .Include(f => f.MealFoods)
            .ThenInclude(mf => mf.Meal) // <--
        .ToListAsync();
    
    0 讨论(0)
提交回复
热议问题