在EF中更新集合

时间:2015-04-03 15:50:04

标签: c# entity-framework collections foreign-keys

您通常如何更新EF中的收藏? 想象一下,我们有一些带有相对表的模型M1,EF表示为ICollection<F1>,可以编写Entities.M1.F1.Where(...)之类的代码。

public partial class M1
    {
        public M1()
        {
            this.F1 = new HashSet<F1>();
        }
        public int Id { get; set; }
        public virtual ICollection<F1> F1 { get; set; }
    }

那么,更新F1与另一个相对集合的最佳方式是什么?
简单分配Entities.M1.F1 = newData;导致数据重复,分配清除Entities.M1.F1.Clear(); Entities.M1.F1 = newData;会产生以下异常:

An error occurred while saving entities that do not expose foreign key properties for their relationships. The EntityEntries property will return null because a single entity cannot be identified as the source of the exception. Handling of exceptions while saving can be made easier by exposing foreign key properties in your entity types. See the InnerException for details.

使用InnerException

{"A relationship from the 'FK_F1_M1' AssociationSet is in the 'Deleted' state. Given multiplicity constraints, a corresponding 'F1' must also in the 'Deleted' state."}

1 个答案:

答案 0 :(得分:0)

目前没有简单的方法来更新EF中的集合。 您需要遍历每个引用对象并在集合中添加/删除。 下面这个例子中的f.x

 var selectedCoursesHS = new HashSet<string>(selectedCourses);
            var instructorCourses = new HashSet<int>
                (instructor.Courses.Select(c => c.CourseID));

            foreach (var course in schoolContext.Courses)
            {
                if (selectedCoursesHS.Contains(course.CourseID.ToString()))
                {
                    if (!instructorCourses.Contains(course.CourseID))
                    {
                        instructor.Courses.Add(course);
                    }
                }
                else
                {
                    if (instructorCourses.Contains(course.CourseID))
                    {
                        instructor.Courses.Remove(course);
                    }
                }
            }

更新后,您需要为您的上下文修改一个状态,然后执行savechanges()

希望这有帮助!!!