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