Reading is to the Mind what Bounded Context is to DDD!!
Typically, for small to medium-sized projects, you probably have a single database context or two, but what if you are working on a large project that requires multiple DbContexts!
As you create the so-called ‘bounded’ contexts (a pattern that was coined by Eric Evans in his ground-breaking book on Domain Driven Design), you need to specify a connection string. In other words, tables that are created in the database are represented as entities in the domain irrespective of the methodology used to create the domain.
A domain is made up classes which are wrapped in a single database context. If you have hundreds of tables and a single domain, then, from the maintenance standpoint, this can potentially be less maintainable. It is therefore a good practice to group these classes in multiple domains or multiple bounded-contexts.
The code below shows a one of the context classes which inherits from the base DbContext class.
Notice the three database contexts in Solution Explorer that we have in the project, each of which is pointing to the same database defined separately in App.Config like so:
Ideally, what we want is to use a single connection to the database.
In order to do that, let’s create a new class and call it BaseContext. The BaseContext is defined as a generic class with a constraint where you are required to pass in value of DbContext.
So instead of having multiple DbContext(s) and having an individual connection string for each, we’d rather have a single connection string and use it for different DbContexts.
Note that BaseContext constructor is marked static. This declaration ensures that the Database Initializer setting is set per an application instance of the given constructor.
In order to do that, modify each one of the dbContext classes to inherit from the BaseContext instead of inheriting from DbContext directly like before. Furthermore, in app.config or web.config, remove additional references to the database and just keep the one as shown below:
Now, when you run the application, EF would produce the same output pointing to a single database albeit multiple contexts through the magic of a generic BaseContext.
If you want to know more about DbContext, I would highly recommend a book by Julie Lerman, titled, Programming Entity Framework: DbContext.