Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When to use DbSet<T>.Add() vs DbSet<T>.Attach()

I have been using Add() and ran into a problem where by a parent entity was being duplicated in the database when Adding a child. Using Attach() solved this but I would like to know why rather than blindly stumbling around.

like image 502
dav_i Avatar asked Apr 11 '13 14:04

dav_i


People also ask

What are the differences between ADD and attach?

Add is to indicate to the Entity Framework that we are going to want to insert a new record in the database. In contrast, Entry and Attach are used in scenarios where the record already exists in the database, and we simply want to make some kind of modification on it. var attach = context.

What does DbSet attach do?

Attach is used to repopulate a context with an entity that is known to already exist in the database. SaveChanges will therefore not attempt to insert an attached entity into the database because it is assumed to already be there.

What is the difference between DbSet and DbContext?

Intuitively, a DbContext corresponds to your database (or a collection of tables and views in your database) whereas a DbSet corresponds to a table or view in your database. So it makes perfect sense that you will get a combination of both!

Which method begins tracking a given entity using the unchanged state by default?

Attach(Object) Begins tracking the given entity and entries reachable from the given entity using the Unchanged state by default, but see below for cases when a different state will be used. Generally, no database interaction will be performed until SaveChanges() is called.


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.

like image 78
Anderson Fortaleza Avatar answered Sep 19 '22 13:09

Anderson Fortaleza


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

like image 29
Manzur Alahi Avatar answered Sep 21 '22 13:09

Manzur Alahi