问题
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