2015-04-03 128 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