When would I want to use the Add method, and not the Attach method?

Viewed 71

I know there are existing/older questions on difference between Add and Attach methods of the DbSet<TEntity> class. To be clear, I'm not asking that question again. I know how they work and the functional difference between them.

What I understand from what they do behind the scene (as described in their documentations) is, Attach completely covers Add's functionality (please correct me if I'm wrong). Better yet, it does that in a more careful way (in disconnected graph, marks an entity as Unchanged instead of Added if it has the PK value set).

That's what makes me wonder about the reason behind the existence of the Add method. I mostly use EF Core with disconnected entities, and there might be scenarios that I'm not aware of.

So, what could be a possible scenario where I might want to use the Add method because the Attach method wouldn't be appropriate?

1 Answers

I see two reasons:

  1. To make code self-explanatory. If you create a new entity object, Add it, don't Attach it. Not all developers will understand that attaching an entity may mark it as Added.

  2. To enforce that an entity is marked for insert. For example when "cloning" an existing entity (i.e. save it as a new database record). EF will mark the existing entity as Added irrespective of its key value(s) and insert it as a new row in the database.

As for the second point, when the primary key is auto-generated, in EF6 that's all there was to it, EF will insert the entity and get its new key value(s) from the database. EF core will try to insert the new entity with existing key values, so you first have to clear them, i.e. set them to their default values.

In short: use Add for code that is designed to add data, Attach when attaching objects that may be any mix of new or existing entities.

Related