I have the following code for editing the departments a user is in. For some reason, method1
causes EF to try and insert the relationship again (and causing a primary key error), where method2
succeeds.
Why does the code of method1
not know that by reassigning the value, I only want the new collection of departments? Is method2
the preferred method to update values? I haven't had to do it this way with one to many relationships.
public class User
{
public string name { get; set; }
public virtual List<Department> Departments { get; set; }
}
public class Department
{
public string name { get; set; }
public virtual List<User> Users { get; set; }
}
public void Method1(list<Department> departments, string userId)
{
var user = DbContext.Users.FirstOrDefault(u=> u.Id == userId);
user.departments = departments;
db.SaveChanges()
}
public void Method2(list<Department> departments, string userId)
{
var user = DbContext.Users.FirstOrDefault(u=> u.Id == userId);
user.departments.clear();
user.departments = departments;
db.SaveChanges()
}