Rushino
Rushino

Reputation: 9495

Entity Framework and entities states

If you load an entity from Entity Framework and you store the reference somewhere. Does entity framework keep trace of the object until it get disposed ? can you save the state of the object anytime ? (How does it keep trace of it) We are talking about an application not a web application.

Upvotes: 1

Views: 107

Answers (3)

angrax
angrax

Reputation: 82

dont forget if you use .AsNoTracking you entity is out of the context and will just a object and you cant persist or make changes.

Upvotes: 1

Pawel
Pawel

Reputation: 31610

If you load an entity it will be tracked in ObjectStateManager until the ObjectContext is disposed. You can load is as no tracking though - with DbContext (or to be more correct DbSet) you can use .AsNoTracking in your query

Upvotes: 1

Paul Fleming
Paul Fleming

Reputation: 24526

For as long as your database context exists, the entity will be tracked. This is assuming you don't manually detach it.

Consider (freehand/pseudo):

MyEntity entity;

using (var context = new MyDbContext())
{
    entity = context.MyEntities.First();
}

entity.Property1 = "something"; // success
entity.LazyNavigationProperty.Property2 = "something"; // fail

The lazy loading will fail because you've disposed the context and the connection with it.

Whereas consider:

var context = new MyDbContext())
MyEntity entity = context.MyEntities.First();

entity.Property1 = "something"; // success

// do loads of stuff

entity.LazyNavigationProperty.Property2 = "something"; // success

context.SaveChanges();

The context is still open so the entity will be tracked and persisted on demand.

Upvotes: 0

Related Questions