Controlling how often an Entity Framework ObjectContext is created

≡放荡痞女 提交于 2019-12-24 01:49:17

问题


I have a rather large SQL backed ASP.NET project that uses Entity Framework to interact with the database.

My question is, should I create an instance of the ObjectContext defined by the edmx/designer files in each class/method -or- wrap it around a static class that would instantiate onload and basically handle all requests through one instance.

I will have multiple users using the ObjectContext to read and update the DB, concurrency and thread safety are my utmost concerns.

EDIT: This code would ultimately run in IIS and be susceptible to recycling.


回答1:


In most cases you just need single context for every request. Only special scenarios can need more contexts per single request but never share context among requests.




回答2:


The ObjectContext class is not thread safe. The integrity of data objects in an ObjectContext cannot be ensured in multithreaded scenarios.

Source: http://msdn.microsoft.com/en-us/library/system.data.objects.objectcontext.aspx

Therefore the best approach is to use an ObjectContext per HTTP request. Make a RepositoryBase class that every repository extends from and in the RepositoryBase define common CRUD operations (preferably generic) and make a new instance of only if it's null on requesting for it.



来源:https://stackoverflow.com/questions/10149980/controlling-how-often-an-entity-framework-objectcontext-is-created

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