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?
In provide code above you are not adding new role as your ctx.Users is just used to retrieve data. Somewhat similar issue is addressed in this SE post – Linq To Entities – how to filter on child entities.
I would advice to look at this short and useful article – Entity Framework 4.0 FAQ – Getting Started Guide.