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

Спасибо. Я подожду еще немного, может быть, другие ответы. Этот вопрос очень важен. –

Смежные вопросы