Code First EF6 - 更新MVC Web应用程序中的多对多关系

时间:2016-03-17 02:55:41

标签: c# repository entity-framework-6

课程与成分之间存在多对多的关系,以及膳食与课程之间的一对多关系。

public MealContext _context = new MealContext();
public IEnumerable<Meal> Meals { get { return  _context.Meals.Include("Courses"); } }
public IEnumerable<Course> Courses { get { return   _context.Courses.Include("Ingredients"); } }
public IEnumerable<Ingredient> Ingredients { get { return _context.Ingredients; }

public class BaseEntity
{
    public int Id { get; set; }
    public DateTime Created { get; set; }
    public DateTime Updated { get; set; }
}

public class Meal : BaseEntity
{
    public string Name { get; set; }
    public List<Course> Courses { get; set; }
}

public class Course : BaseEntity
{
    public string Name { get; set;}
    public Meal Meal { get; set; }
    [ForeignKey("Ingredients")]
    public List<int> IngredientIds { get; set; }
    public List<Ingredient> Ingredients { get; set; }
}

public class Ingredient : BaseEntity
{
    public string Name { get; set; }
}

public bool AddMeal(ref Meal meal)
{
    try
    {
        _context.Meals.Add(meal);
        foreach (var course in meal.Courses)
        {
            course.Created = DateTime.Now;
            course.Updated = DateTime.Now;

            _context.Courses.Add(course);
            if(course.Ingredients == null) { course.Ingredients = new List<Ingredient>(); }
            foreach (var ingredient in course.Ingredients)
            {
                _context.Entry(ingredient).State = EntityState.Modified;
            }
        }
        meal.Created = DateTime.Now;
        meal.Updated = DateTime.Now;
        _context.SaveChanges();
        trans.Commit();
        return true;
    }
    catch (Exception ex)
    {
        Logger.Error(ex.Message + "\n" + ex.StackTrace);
        trans.Rollback();
        return false;
    }
}        

在用餐创建视图中,我可以添加课程到餐,并添加成分到课程。一切都按预期工作。

然而,当我尝试编辑一顿饭时,所有课程的成分变化都没有得到保存,也没有任何例外。

我的视图使用在编辑器模板中生成的下拉列表来填充IngredientIds集合,并且我已经验证列表在到达我的存储库时已填充并正确。

我尝试从数据库加载每个课程对象,使用_context.Entry(dbCourse).CurrentValues.SetValues(course)将被跟踪对象的每个值设置为未跟踪对象的值。

我尝试通过Id(course.Ingredients = _context.Ingredients.Where(i =&gt; course.IngredientIds.Contains(i.Id));)将成分加载到数据库的列表中。 / p>

我尝试使用_context.Entry(成分)标记每个成分.State = EntityState.Modified。

我所做的一切似乎都无法奏效,而且我已经完成了关于该主题的每个StackOverflow帖子(大部分归结为上述三种解决方案中的一种)。

如何正确保存这些关系?

目前,我的更新功能如下所示:

public bool UpdateMeal(ref Meal meal)
{
    using (var trans = _context.Database.BeginTransaction())
    {
        try
        {
            meal.Updated = DateTime.Now;
            if (meal.Courses != null)
            {
                foreach (var course in meal.Courses)
                {
                    course.Updated = DateTime.Now;
                    if (course.IngredientIds != null && course.IngredientIds.Count > 0)
                    {
                        var newIngredients = _context.Ingredients.Where(i => course.IngredientIds.Contains(i.Id)).ToList();
                        course.Ingredients = newIngredients;
                    }
                    var dbCourse = _context.Courses.Include("Ingredients").Single(c => c.Id == course.Id);
                    _context.Entry(dbCourse).CurrentValues.SetValues(course);
                }
            }
            _context.SaveChanges();
            trans.Commit();
            return true;
        }
        catch (Exception ex)
        {
            Logger.Error(ex.Message + "\n" + ex.StackTrace);
            trans.Rollback();
            return false;
        }
    }
}

2 个答案:

答案 0 :(得分:0)

我会帮助将导航属性更改为virtual,以便Entity Framework可以创建延迟加载代理。

示例:

public virtual List<Ingredient> Ingredients { get; set; }
public virtual Meal Meal { get; set; }

你可能需要告诉EF你的关系。为此,请将流动方法添加到DbContext:

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
    // One to many
    modelBuilder.Entity<Meal>()
        .HasMany(x => x.Courses)
        .WithRequired(x => x.Meal);

    // Many to many
    modelBuilder.Entity<Course>()
        .HasMany(x => x.Ingredients)
        .WithMany();
}

答案 1 :(得分:0)

课程需要virtual ICollection<Ingredient>,而成分需要virtual ICollection<Course>。 EF应该创建一个名为IngredientCourses或CourseIngredients的连接表。我做了一个快速测试模型

public class Meal
    {
        public int Id { get; set; }
        public virtual ICollection<Course> Courses { get; set; }
    }

    public class Course
    {
        public int Id { get; set; }
        public int MealId { get; set; }
        public virtual Meal Meal{ get; set; }
        public virtual ICollection<Ingredient> Ingredients { get; set; }
    }

    public class Ingredient
    {
        public int Id { get; set; }
        public virtual ICollection<Course> Courses { get; set; }
    }

并创造了新的一餐......

    private void OnLoaded(object sender, RoutedEventArgs e)
    {
        using (var context = new MealContext())
        {
            var meal = new Model.Meal();
            var course = new Model.Course();
            var ingredient = new Model.Ingredient();
            var ingredient2 = new Model.Ingredient();
            course.Ingredients = new[] { ingredient, ingredient2 };
            meal.Courses = new[] { course };
            context.Meals.Add(meal);
            context.SaveChanges();
        }
    }

最后以enter image description here

结束