3

I am reading this E.F. Team Blog's this series http://blogs.msdn.com/b/adonet/archive/2011/01/27/using-dbcontext-in-ef-feature-ctp5-part-1-introduction-and-model.aspx

At many places i saw this term "Entity Tracked by Context", specially in this part http://blogs.msdn.com/b/adonet/archive/2011/01/29/using-dbcontext-in-ef-feature-ctp5-part-4-add-attach-and-entity-states.aspx (part4)

My questions are

  1. What does "Entity Tracked by Context" mean??

  2. Does same context is used for every request or new context is created for each request (I am using E.F. for Asp.Net MVC APP)

  3. Tracking every entity (loaded) must be adding some memory-overhead on server, is it??

Praveen Prasad
  • 29,661
  • 16
  • 67
  • 104

1 Answers1

4

"Entity Tracked by Context" mean that context is aware of the entity, it knows state of the entity and changes made to the entity. Context can work only with tracked entities. If you call save changes only changes on tracked entities will be persisted to the database. Tracked and Attached can be considered as synonyms.

In EF we are usually talking about attached entities and detached entities. Attached entities are tracked by the context. Entity become attached if you load it from database (unless you manually for EF to don't track the entity) or if you call Attach or Add (DbContext API) / AddObject (ObjectContext API) for the entity. You can force entity to detach from the context either by calling Detach (ObjectContext API) or setting the state to Detached (DbContext API). If you just create the entity in your code as any other class it is considered as detached until you call Attach for it.

New context is always created for each request - web application works a lot with detached entities. That will also solve the issue with memory. If you detach all entities you want to store in some state (like session) and if you dispose the context correctly in each request you will free the memory.

Community
  • 1
  • 1
Ladislav Mrnka
  • 349,807
  • 56
  • 643
  • 654