Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiple DbContext classes for a single web app. Good or bad?

Is it a good practice to have multiple XXX : DbContext classes for each major section of a web application (considering it's a big one with at least 50 tables in its database)? For example: MembershipContext, BlogContext, StoreContext etc. Or it's more convenient to have a single DatabaseContext for all the db access related stuff.

like image 785
Grief Coder Avatar asked Jun 17 '12 16:06

Grief Coder


People also ask

Can we have multiple DbContext?

In code first, you can have multiple DBContext and just one database. You just have to specify the connection string in the constructor.

Why do we use DbContext in MVC?

DbContext is a class provided by Entity Framework to establish connection to database, query the db and close connection. Extending DbContext permits to define database model with DbSet (specific Set mapped to a table or more), create a database, query a database...

What is application DbContext?

The DbContext class is an integral part of Entity Framework. An instance of DbContext represents a session with the database which can be used to query and save instances of your entities to a database. DbContext is a combination of the Unit Of Work and Repository patterns.

What is DbContext in asp net?

DbContext is an important class in Entity Framework API. It is a bridge between your domain or entity classes and the database. DbContext is the primary class that is responsible for interacting with the database.


1 Answers

Using multiple DbContext classes implies complicating cross-transactions (you can find a solution to this problem on the web here an example http://pastebin.com/YEDqyH0n) but may be justified. It all depends on your architecture and the separation that you want to design.

Anyways you should look at the Repository and UnitOfWork patterns to have a layer of abstractation of how to use your DbContexts. Look here: Multiple DbContexts in N-Tier Application and here EF and repository pattern - ending up with multiple DbContexts in one controller - any issues (performance, data integrity)? if you use ASP.NET MVC.

For 50 tables I think it may be justified to have multiple DbContexts. So I would recommend using multiple DbContexts. But you should wrap them using the Repository and UnitOfWork patterns to be independant from the actual implementation in the other layers (like this you could easily change your mind later and only use a signle DbContext for example).

I hope that helps.

like image 53
Jason De Oliveira Avatar answered Oct 21 '22 20:10

Jason De Oliveira