What does “Entity Tracked by Context” mean in Entity Framework

不想你离开。 提交于 2019-12-10 18:45:19

问题


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??


回答1:


"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.



来源:https://stackoverflow.com/questions/6447099/what-does-entity-tracked-by-context-mean-in-entity-framework

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!