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.
In code first, you can have multiple DBContext and just one database. You just have to specify the connection string in the constructor.
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...
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With