Successfully added
Provide more details
by Elvin
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 associatedCategory
object to Unchanged in the_dbContext
. This indicates that theCategory
object is not modified and should not be updated in the database. - For each
Role
, it sets the state toDetached
. Detaching an entity means it is no longer tracked by the EF Core context for changes. - The
IsModified
property of theRoles
collection in theelement
is explicitly set tofalse
. This indicates to EF Core that theRoles
collection has not been modified and should not be updated in the database.
Referenced in:
Comments