Aflred
Aflred

Reputation: 4593

How does the dbContext track the state of an entity

Im talking about asp.net mvc so basically an instance of the dbcontext gets initialized, puts the data in the view then it gets disposed of.

how does it track changes made to the entity if the "entry" which contains the original and present value get ...well disposed of.

Upvotes: 0

Views: 190

Answers (1)

Tomi Lammi
Tomi Lammi

Reputation: 2126

Well, it doesn't.

Let's say you fetch an entity from the database for an edit view. Then the edit view is generated from the entity. Now the context is disposed, as it is not needed anymore. We have all the data needed to create view. Context doesn't track any changes you do in the view and when you think about it, how could it anyway?

Now you post the edit view. Context has no idea that the model has been changed. On the edit action method you mark the posted entity as dirty with db.Entry(entity).State = EntityState.Modified that doesn't do anything yet really, but when you call db.SaveChanges all the dirty entities are updated, added or deleted. After this the context is disposed again.

The point is EF doesn't track the changes for you, it's you who decides which entities are being updated. It updates the entity yes, but it doesn't know what has been changed since the last update (atleast I think so, why would it need to track the changes?).

Upvotes: 1

Related Questions