This question is a continuation of:
EntityFramework adding new object to a collection
Now I understand that when using DbSet
EF won't load the entire collection into memory
But what if I have something like the following code:
public class User
{
public int UserID { get; set; }
public string UserName { get; set; }
public ICollection<Role> Roles { get; set; }
}
public class Role
{
public int RoleID { get; set; }
public string RoleName { get; set; }
public User User { get; set; }
}
public class MyContext : DbContext
{
public DbSet<User> Users { get; set; }
public DbSet<Role> Roles { get; set; }
}
public class SomeClass
{
public void AssignRoleToUser(int userID, Role role)
{
var ctx = new MyContext();
var user = ctx.Users.First(x => x.UserID.Equals(userID));
user.Roles.Add(role);
ctx.SaveChanges();
}
}
In this case, I'm not using the DbSet
object to add a new object to the Role collection, instead, I'm adding a new role to a specific user using an ICollection
collection
So what happens in this case?
Does EntityFramewrk have to load into memory all the user's roles in order to perform the insert?