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.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With