0

Let's say I've got an entity Student and it has related entities Classes.

I need logic to assign new Classes that would replace existing Classes

I'm using Entity Framework, and these classes are mapped to a database, so when DbContext.SaveChanges() is executed, it should replace old records with the new ones.

Here is sort of a pseudo code for this - the version with AddRange() works, but version with Classes = NewClasses.ToList(); - adds new classes but does not remove the old ones.

Can anyone explain why just assigning a list is not removing the old records?

public class Student 
{
    public List<Class> Classes { get; set;}

    public void UpdateClassesA(ICollection<Class> newClasses)
    {
        //this just adds new classes, but doesn't remove the existing ones (when EF SaveChanges is performed)
        Classes = newClasses.ToList();
    }

    public void UpdateClassesB(ICollection<Class> newClasses)
    {
        Classes = new List<Class>();
        Classes.AddRange(newClasses);
    }
}
marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Prokurors
  • 2,458
  • 3
  • 40
  • 65
  • 1
    This helps? https://stackoverflow.com/questions/30116199/entity-framework-proper-way-to-replace-collection-in-one-to-many – dani herrera Jun 26 '22 at 16:46
  • I have loaded the related collection with `Include(x => x.Classes)` but somehow that was not enough in my case – Prokurors Jun 26 '22 at 17:43

0 Answers0