0

How you usually update collection in EF? Imagine, that we have some model M1 with relative table, which EF presents as ICollection<F1> and can write code like 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; }
    }

So, what is the best way to update relative collection of F1 with another one?
Simple assignment Entities.M1.F1 = newData; results data duplication, assignment with clearing Entities.M1.F1.Clear(); Entities.M1.F1 = newData; produces following exception:

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.

with the 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."}
elixenide
  • 44,308
  • 16
  • 74
  • 100
Arman Hayots
  • 2,459
  • 6
  • 29
  • 53

1 Answers1

0

currently there is no straightforward way to update collection in EF. you need to go through each reference object and add/remove in collection. f.x in this example below

 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);
                    }
                }
            }

once you update this you need to make a state as modified for your context and then do savechanges()

hope this help!!!

nikudale
  • 399
  • 2
  • 12