Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between IDbSet.Add and DbEntityEntry.State = EntityState.Added?

In EF 4.1+, is there a difference between these 2 lines of code?

dbContext.SomeEntitySet.Add(entityInstance);
dbContext.Entry(entityInstance).State = EntityState.Added;

Or do they do the same thing? I'm wondering if one might affect child collections / navigation properties differently than the other.

like image 244
danludwig Avatar asked Jan 31 '12 16:01

danludwig


People also ask

What does EntityState Modified do?

Updates are not sent to the database for entities in the Unchanged state. Added entities are inserted into the database and then become Unchanged when SaveChanges returns. Modified entities are updated in the database and then become Unchanged when SaveChanges returns.

What is EntityState?

The Entity state represents the state of an entity. An entity is always in any one of the following states. Added: The entity is marked as added. Deleted: The entity is marked as deleted. Modified: The entity has been modified.

How does DbContext change state of entity?

This can be achieved in several ways: setting the EntityState for the entity explicitly; using the DbContext. Update method (which is new in EF Core); using the DbContext. Attach method and then "walking the object graph" to set the state of individual properties within the graph explicitly.


1 Answers

When you use dbContext.SomeEntitySet.Add(entityInstance); the status for this and all its related entities/collections is set to added, while dbContext.Entry(entityInstance).State = EntityState.Added; adds also all the related entities/collections to the context but leaves them as unmodified. So if the entity that you are trying to create has a related entity (and it's value its not null), when you use Add it will create a new object for that child entity, while with the other way it won't.

like image 69
fbiagi Avatar answered Sep 20 '22 14:09

fbiagi