EntityFramework adding new object to nested object collection

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.


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

<ol> <li>

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

</li> <li>

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'

</li> <li>

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.

</li> </ol>

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.


  • Get correct checkbox value when using razor asp.net mvc
  • Convert Future[List[String]] to List[String]
  • How to implement a relationship between IdentityRole (dbo.AspNetRoles) and a custom entity?
  • How to make SQL Query to get the sum of specific column?
  • Bootstrap tag typeahead input not populating menu with jQuery ajax
  • Update foreign key using Entity Framework
  • AngularJS: accessing scope variables in $routeProvider
  • How to escape wildcard expansion in a variable in bash?
  • Mockito: Mock class object
  • Jquery selector finding input inside fieldset
  • Get storage account of Azure VM
  • Chart js - Draw center of each bubbles of a bubble chart
  • Calling Generic Property In Generic Class From Interface Implemented By Generic Class
  • Multiple auth user types in Laravel 5
  • How to check if a RxJS Observable contains a string in Angular2?
  • How to use AWS roles with Packer to create AMIs
  • Handle Authentication and Authorization in jax-rs webservice with cxf
  • Serverless Framework Dynamo DB Table Resource Definition with Sort Key
  • Laravel 5.1 Multitenancy setup
  • Symfony2 plaintext users don't work
  • JsonMappingException: Can not deserialize instance of java.lang.Integer out of START_OBJECT token
  • Change navbar in bootstrap if user login
  • Yii2 Login with database
  • Can't access Tomcat 7 Manager app when running from Eclipse
  • Is it better to have roles as a column on my users table, or do it through join tables (Roles &
  • How to concat Pandas dataframe columns
  • Action Pack components in Rails
  • how to get username into sql trigger when multiple users signed on from asp membership
  • close() was never explicitly called on database
  • Button click event not firing in jQuery
  • Chart.js Multiple dataset
  • How to render a blob on a canvas element?
  • Can a Chrome extension content script make an jQuery AJAX request for an html file that is itself a
  • How to delete a row from a dynamic generate table using jquery?
  • using HTMLImports.whenReady not working in chrome
  • Authorize attributes not working in MVC 4
  • unknown Exception android
  • Checking variable from a different class in C#
  • failed to connect to specific WiFi in android programmatically
  • How can I use threading to 'tick' a timer to be accessed by other threads?