Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How Many DBContext's Should I have

Using Entity I currently have dbcontext that has every table in it.

I'm wondering if that's what everyone does, or do you have a context per module for example. To me the dbcontext was a connection to map the models to a database, and since there is only one database, I only need one.

Before I get too far along I want to see if that's appropriate.

So 1 db context per database or many?

like image 830
Dale Fraser Avatar asked Apr 27 '13 03:04

Dale Fraser


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. Yes you can, but how can you query from different entities from different db contexts?

Should DbContext be a singleton?

First, DbContext is a lightweight object; it is designed to be used once per business transaction. Making your DbContext a Singleton and reusing it throughout the application can cause other problems, like concurrency and memory leak issues.

Should you use using with DbContext?

EF and EF Core DbContext types implement IDisposable . As such, best practice programming suggests that you should wrap them in a using() block (or new C# 8 using statement). Unfortunately, doing this, at least in web apps, is generally a bad idea.

What are the disadvantages of using static DbContext?

If you only use one DbContext instance and lock it for thread safety, so you only have one connection to DB. If your website have hundreds of request per second then all of them have to queue to use the only connection. In that case, DbContext object became the perfomance bottleneck of your system.


1 Answers

I went through this same process recently and found some great resources on the subject. Here are a couple that were very helpful:

  • Shrink EF Models with DDD Bound Contexts.
  • How to decide on a lifetime for your ObjectContext.

I was building a Desktop app, and I ended up using multiple contexts so that I could keep the lifetime tied to the module rather than the application. This has worked out very well for me, and I like that my DbContext isn't swamped with DbSets and is limited to the ones that are relevant for the current module.

In an ASP.NET MVC app, it is different since the DbContext will only live as long as the request, and in those cases, I usually use a single DbContext to simplify things unless the database is very large. With a large database, I would probably break it apart into multiple DbContexts just to limit the overhead and the clutter, and keep things compartmentalized.

like image 172
Brian S Avatar answered Sep 17 '22 12:09

Brian S