Using the same DbContext object across different controllers

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

Question

I am coding a MVC 5 internet application & have a question in regards to using the same instantiated DbContext object across different controllers.

I am wanting to do this because i am retrieving some of the same data in different controllers, & the inbuilt caching feature of the DbContext class will minimize many database transactions.

Here is some code to explain:

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

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

What would be the best way to code this and are there any disadvantages to this? Should each user have their own DbContext object, or only one for all users? What should I be aware of before coding this? Could potential conflicts occur when CRUD actions occur?

Thanks in advance.

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

Accepted Answer

You should not have the same dbContext for all controllers. It is not a good practice to do so because that way the framework has to track a lot more entities and if something goes wrong on EF side, it will be difficult to debug too. Use one dbContext per controller class.

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

Popular Answer

You can also use a class as wrapper and put a static reference to the dbcontext.



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