2

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?

Community
  • 1
  • 1
Jupaol
  • 21,107
  • 8
  • 68
  • 100
  • in this provide code, above you are not adding new role as your ctx.Users is just use to retrieve data. – Yusubov Dec 13 '12 at 20:44

2 Answers2

1

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.

Community
  • 1
  • 1
Yusubov
  • 5,815
  • 9
  • 32
  • 69
1

No. EF does not need to know what 'Roles' the User has. You need to learn what happens in regards to change tracking:

  1. Once the query is run the change tracker receives an object entry for 'user'. The state of this user is 'Unchanged'

  2. You add a new role to the user's Roles collection. This simply adds a change tracker entry for this new role and marks it as 'Added'

  3. On SaveChanges() EF will look at your change tracker and see that the user object has not changed so nothing needs to be done there. There is also an entry for the new role which states that it needs to be added. So an SQL query will be written to insert this role.

Simple as that. You can always debug and add a watch for the state of the change tracker. The entries can be found by calling DbContext.ChangeTracker.Entries().

EF will blindly send off the 'add' to the DB.

refactorthis
  • 1,893
  • 15
  • 9