I have a project called MyApp.DataAccess which contains several database contexts. This started as one context and has grown to three (all separate databases required for my app). As you can imagine I have Initializer classes for each as well and I’m also now trying to use Migrations. I can see that this will really clutter up my MyApp.DataAccess project.
I also have a project called MyApp.Model which contains model classes which are generally organized in folders per their use in each aforementioned Context.
I’m struggling with how best to organize multiple DbContexts and Model classes.
My instinct tells me option 1 but what is the best practice?
-
Create a MyApp.DataAccess.[ContextName] project for each DbContext which contains the DbContext, migrations, and relevant Model classes. Ultimately I’ll still need a MyApp.Model project to represent non-database Model classes.
-
Create a MyApp.DataAccess.[ContextName] project for each DbContext which contains ONLY the DbContext and Migrations; continue to use the MyApp.Model for ALL model classes (organized in folders and sub-namespaces).
-
Do nothing — a single MyApp.DataAccess with multiple DbContexts, multiple migrations, etc.; a single MyApp.Model with Models for multiple databases organized by folder.
What is the best practice / ideal approach?
Your question should start with “why should I have different DbContexts”. In most cases different contexts mean different data models, different – unrelated – responsibilities, and thus should be as well separated as that’s possible. Which means that different assemblies are go.