I have been using Add()
and ran into a problem where by a parent entity was being duplicated in the database when Add
ing a child. Using Attach()
solved this but I would like to know why rather than blindly stumbling around.
Well, when you use Attach
you tell the context that the entity is already in the database, SaveChanges
will have no effect over attached entities. Add
, on the other hand, changes the state of the entity in the context (if it's already there) to Added
, meaning it will always insert the entity in the database when you call SaveChanges
.
That's the difference.