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.

- 27,509
- 17
- 104
- 136
-
I think this http://stackoverflow.com/questions/3920111/entity-framework-4-addobject-vs-attach will hopefully answer your question – Conrad Clark Apr 11 '13 at 14:18
-
Thanks. This also helped: http://stackoverflow.com/a/15310068/1185053 – dav_i Apr 17 '13 at 11:09
2 Answers
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.

- 2,449
- 20
- 22
-
Thanks for the response. Why then in an auto-generated `Controller` in Edit does it use `db.Entry(model).State = EntityState.Modified; db.SaveChanges();` and not `Attach()`? – dav_i Apr 12 '13 at 16:08
-
2Because when you `Attach()` an entity that is already in the **context**, as it is the case of the entity stored at the `model` variable, it sets the entity's state to `Unchanged`, therefore if you use `Attach()` for this end your entity will not be updated when you call `SaveChanges()`. – Anderson Fortaleza Apr 12 '13 at 16:30
in case of ef-core
Attach is good for cases when you are adding a new entity to the database with navigational properties. Attach only marks newly created items as changed.
Let's say you are adding a new Employee to an Industry. If the industry already exists in the database it must have an ID. and the Employee you are adding is not inserted to the database yet so it does not have an ID yet (I am talking about row IDs here).
So what attach does is since the Industry already has an ID. Attach marks that as Unchanged. And your Employee who doesn't have an ID yet attach marks it as Added.
You can read more about this topic here: https://www.learnentityframeworkcore.com/dbcontext/modifying-data#attach

- 1,870
- 23
- 19
-
2It should be clear that EF6 and EF-core are different here. EF6 won't mark an attached entity as `Added`. – Gert Arnold Apr 30 '20 at 20:56