简体   繁体   中英

Navigation Property Not being Added In Entity Framework 7 using vNext

public void AddMeal(MealModel mealModel)
    {
        using (var context enter code here= new HealthContext())
        {
            var meal = new Meal
            {
                MealNumber = mealModel.MealNumber,
                MealEntries = new List<MealEntry> { new MealEntry { FoodId = 1, MealEntryNumber = 1, Calories = 250, MealId = 1 } },
                DayId = mealModel.Date
            };
            context.Meals.Add(meal);
            context.SaveChanges();
        }
    }

I am using Entity Framework 7 with code first migrations and am trying to add a new "Meal" to the database.

The "Meal" is added successfully with the 2 columns listed above, but the "MealEntries" are not added. MealEntries is an ICollection of MealEntry that is used as a navigation property that exists on the "Meal" Entity.

In this code example I even hard-coded the new "List" to see if that would work, but even that is not being added to the database.

1 odd thing I noticed while debugging the code was that after stepping over the "Add" command, all of the primary keys and/or foreign keys were set to negative values by EF, except for the "Id" of each "MealEntry" in the "MealEntries list. It's almost like EF is not tracking this list and thus will not update it.

What do I need to do to have a navigation property that is a list be "bulk" added 1 by 1 into its respective table in the database when I add a "Meal"?

In EntityFramework 7, at this point in time, child members are not automatically added. You have to explicitly add them yourself.

context.Meals.Add(meal);
context.MealEntries.AddRange(meal.MealEntries);
context.SaveChanges();

Relevant github issue discussing this.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM