Using the same DbContext object across different controllers

asp.net-mvc-5 c# controller dbcontext entity-framework-6

Question

I have a question about using the same instantiated object in an MVC 5 internet application that I am currently creating.DbContext item between various controllers.

Because I'm retrieving parts of the same data from several controllers and the built-in caching capability of theDbContext reducing the number of database transactions by the class.

The following code will explain:

public class TestController1 : Controller
{
    private CanFindLocationDatabaseContext db = new CanFindLocationDatabaseContext();
}

public class TestController2 : Controller
{
    private CanFindLocationDatabaseContext db = new CanFindLocationDatabaseContext();
}

What would be the most effective method to code this, and are there any drawbacks? Should there be a separate DbContext object for each user or just one for all users? What should I understand before I code this? When CRUD tasks are performed, may there be potential conflicts?

I appreciate it.

1
1
5/19/2015 5:49:59 AM

Accepted Answer

The same dbContext shouldn't be used by all controllers. It is not a good idea to do this because the framework will have to keep track of a lot more things, and if something goes wrong with EF, it will be challenging to troubleshoot. Each controller class should have its own dbContext.

-1
5/19/2015 9:08:11 AM

Popular Answer

You can also include a static reference to the dbcontext in a class that serves as a wrapper.



Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow