More than one data context per request
Using more than one data context per request is generally a bad practice. Here is why:
- Each data context has its own database connection. Using more than one data context means using more than one database connection per request, resulting in additional strain on the database and slower overall performance.
- Typically we expect the data context to keep track of our entities. When we have a multiple data contexts, each data context is not aware of the entities that tracked by the other data context and might have to query the database again for its current state or have to issue an unnecessary update.
- Having more than a single data context also means that we can't take advantage on Linq To Sql Unit of Work and have to manually manage our entities' change tracking and we might end up with multiple instances of the same entities in the same request (which using a single data context for the whole request would prevent).
- Having more than one data context means that the ORM have more work to do. In most cases, this is unnecessary and should be avoided.
It's usually recommended to use one data context per request. You should investigate the Session Per Request pattern.
Typically this situation results from micromanaging the data context, meaning that we open the data context just before the query and close it immediately after the query or operation is executed. For example, see the following code:
public Post GetPostbyId(int id) { using (var ctx = new MyBlogContext()) { return ctx.Posts.Where(x=>x.Id = id).FirstOrDefault();
} }
It's strongly recommended to use a contextual data context, such as the one that can be found in the link above.