Insert Entity without updating related Entities

This code sample show how to insert an entity Element without updating related entities.

_dbContext.Entry<Element>(element).State = EntityState.Added;

// Set the state of the Category navigation property of 'element' to Unchanged
_dbContext.Entry<Category>(element.Category).State = EntityState.Unchanged;

// Detach all roles associated with the 'element' from the DbContext
element.Roles.ToList().ForEach(r => _dbContext.Entry<Role>(r).State = EntityState.Detached);

// Mark the Roles collection of 'element' as not modified to prevent updating roles
_dbContext.Entry<Element>(element).Collection(r => r.Roles).IsModified = false;

await _dbContext.SaveChangesAsync();
  • The element's associated Category object to Unchanged in the _dbContext. This indicates that the Category object is not modified and should not be updated in the database.
  • For each Role, it sets the state to Detached. Detaching an entity means it is no longer tracked by the EF Core context for changes.
  • The IsModified property of the Roles collection in the element is explicitly set to false. This indicates to EF Core that the Roles collection has not been modified and should not be updated in the database.

Comments