What is the difference between Add and Attach in Entity Framework, and how can I fix my problem?

c# entity-framework


Since I just recently began using Entity Framework, determining whether or not I really need to add new entries to the database has been quite difficult.

I will be able to tell whether the Entity I need to add to the database is already there because I query the database before adding it. If it is already, I maintain the instance since I need to utilize the Entity in certain relationships.

Consider that the name of my entity isBook .

When an object is missing from the database, there is an issue, and I do:

Book b = //...

I could accomplish:


This will function properly each time I add a new entity (regardless of what form of entity it is), since I'll avoid duplicate entry issues by adding one kind of entry at a time and checking to see whether it already exists in the database.

But what if I don't want to call?SaveChanges() such a lot?

The approach described by the question's author, Is it feasible to determine if an object in Entity Framework has previously been connected to a data context?, sort of helps me in my situation, but it does not work if IAdd the subject of the setting as opposed toAttaching it.

What is the difference between Add and Attach, and how can I resolve my issue? I suppose I have two questions, but they are both highly linked.

Here is an illustration of the issue I'm experiencing.

I have a thing.Result that is connected to two further entities:Trainer and Horse .

I have to manually generate all of the entities since I obtain the data from an outside source.

whenever I want to insert a newTrainer , I do:

var trainer = Trainer.CreateTrainer(Id)

I then do a database query to check whether there is a trainer with that.Id already exists in the database. If so, then I change thetrainer with the database's version of the variable.

If not, I have two options here:

  • Identify the situation and the trainer (I can check if it already exists using the key)
  • Contextualize the trainer (usingAddToTrainers(...) )

similar procedure forHorse .

Now, if I want to make a newResult (it includes aTrainer and aHorse ), I provide that outcome instance the former trainer and horse.

What need I do in order to add this new information to the context?Result ?

  • When I connect the trainer/horse, I receive the desired outcome.InvalidOperationException letting me know that the trainer is now focused on the object context.
  • A other error—which I can't recall right now—tells me that there is already a Trainer in the database if I add the trainer as opposed to attaching it.

While attaching the results, the first error is shown, and the second one appears when doingSaveChanges() .

Calling is what I want to avoid doing here.SaveChanges() whenever I upload a fresh result.

5/23/2017 12:34:09 PM

Accepted Answer

ObjectContext All entities that were added, associated, or loaded by context are tracked internally. Only these entities are capable of database modification whenSaveChanges is invoked. Each of these things has aObjectStateEntry in theObjectStateManager One of the key characteristics of theObjectStateEntry is aState The state is of the type enum.EntityState It provides these benefits:

  • Added
  • Deleted
  • Detached
  • Modified
  • Unchanged

When the database is loaded, each entity is inUnchanged state. A unique state is detached. You won't discoverObjectStateEntry in the Detached stateObjectStateManager . But if you inquireObjectStateManager as theObjectStateEntry For each entity not monitored by the context, a new record will be created.ObjectStateEntry with Detached state.

The distinction between nowAttach and AddObject :

  • Attach - If this method is calledObjectContext will begin monitoring the whole object graph (main entity and all related entities). All entities that have not yet been tracked will be marked asUnchanged state.
  • AddObject - If this method is calledObjectContext will also begin monitoring the whole object graph (main entity and all related entities). The distinction is that any items that have not yet been tracked will be assigned toAdded state (i.e., new items that need to be added to the database).
4/20/2011 7:54:11 AM

Popular Answer

I'm aware that I am a little bit behind the curve on this, but I was searching for a similar solution when I came across this Microsoft article, which may simply address the most of the OP's queries and benefit future SO visitors.

7-zzzzzzz == ( http://msdn.microsoft.com/en-us/data/jj592676.aspx )

Citing the article:

This topic will cover how to add and attach entities to a context and how Entity Framework processes these during SaveChanges.

Additionally, take a close look at the last paragraph there:

Insert or update pattern: A common pattern for some applications is to either Add an entity as new (resulting in a database insert) or Attach an entity as existing and mark it as modified (resulting in a database update) depending on the value of the primary key.

Related Questions


Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow