Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I detach objects in Entity Framework Code First?

People also ask

What is detached state in entity Framework?

Detached is the default state of a newly created entity because the context can't track the creation of any object in your code. This is true even if you instantiate the entity inside a using block of the context. Detached is even the state of entities retrieved from the database when tracking is disabled.

What is attach in entity Framework?

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.


This is an option:

dbContext.Entry(entity).State = EntityState.Detached;

If you want to detach existing object follow @Slauma's advice. If you want to load objects without tracking changes use:

var data = context.MyEntities.AsNoTracking().Where(...).ToList();

As mentioned in comment this will not completely detach entities. They are still attached and lazy loading works but entities are not tracked. This should be used for example if you want to load entity only to read data and you don't plan to modify them.