2015-04-03 96 views
0

如何通常更新EF中的集合? 想象一下,我们有一些型号为M1的相关表,其中EF表示为ICollection<F1>并且可以编写像Entities.M1.F1.Where(...)这样的代码。更新EF中的集合

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."} 

回答

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()

希望这帮助!

+0

谢谢。 我会多等一会儿,也许另一个答案。 这个问题非常重要。 – 2015-04-03 17:51:55