<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Keenan Du Plessis on Medium]]></title>
        <description><![CDATA[Stories by Keenan Du Plessis on Medium]]></description>
        <link>https://medium.com/@keenan.dup137?source=rss-7645f3e58f95------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*4tI2jB1Yb7hirVLXARl89Q.png</url>
            <title>Stories by Keenan Du Plessis on Medium</title>
            <link>https://medium.com/@keenan.dup137?source=rss-7645f3e58f95------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 24 Nov 2026 03:39:13 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@keenan.dup137/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Adding multiple DBContexts to one solution/assembly — ASP.NET(MVC)]]></title>
            <link>https://medium.com/@keenan.dup137/adding-multiple-dbcontexts-to-one-solution-assembly-asp-net-mvc-b17b1a96e11c?source=rss-7645f3e58f95------2</link>
            <guid isPermaLink="false">https://medium.com/p/b17b1a96e11c</guid>
            <category><![CDATA[aspnetcore]]></category>
            <category><![CDATA[aspnet-mvc]]></category>
            <category><![CDATA[dbcontext]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[code-first-approach]]></category>
            <dc:creator><![CDATA[Keenan Du Plessis]]></dc:creator>
            <pubDate>Sun, 12 Nov 2023 15:47:45 GMT</pubDate>
            <atom:updated>2023-11-14T10:01:13.762Z</atom:updated>
            <content:encoded><![CDATA[<h3>Adding multiple DBContexts to one solution/assembly — ASP.NET(MVC)</h3><figure><img alt="A header image for this article: A heart with a processing chip on it with the text “DB Context”." src="https://cdn-images-1.medium.com/max/1024/1*H9UGXoKjBeAxdTIa2JvNHw.jpeg" /><figcaption>Generated with Bing</figcaption></figure><p><strong>Note: </strong>I’m not an expert. I’m just sharing the solution I came up with for doing this. There might be an easier way but I didn’t find one, and that’s why I chose to write this article. Feel free to share your knowledge on the matter in the comments for us all to learn from :).</p><h3>What you need to know before we get started:</h3><p>The solution in question was created using ASP.NET Core 6 and it follows a code-first approach for managing the database schema through migrations.</p><p><strong>NB:</strong> I’m not going to be teaching you how to do everything, you should already know how to set up a database in ASP.NET Core using a code-first migrations approach.</p><h3>Problem Statement:</h3><p>You need to add a<strong> new database context</strong> to a solution that already has one.</p><h3>The obstacles you have to overcome:</h3><ul><li>The 2 DbContexts will be in the <strong>same assembly</strong> so they will both see all the tables created in the solution, not just the ones that they care about.</li><li>The solution already has a DbContext set-up. The way it is set up won’t allow you to just add another DbContext, you will have to restructure the files &amp; folders to accommodate the new DbContext.</li></ul><h4>📖 Glossary</h4><blockquote><strong>OldDbContext </strong>— Refers to the DbContext that was already present.</blockquote><blockquote><strong>NewDbContext </strong>— Refers to the new DbContext that you’re adding.</blockquote><blockquote><strong>Tip:</strong> If you’re missing some code, you have errors in your code, or the instructions don’t make sense, then read a bit further to see if I don’t address the problem/s you’re facing.</blockquote><h3>Step 0: Create a new ConnectionString</h3><p>We need a new ConnectionString if we’re going to be adding a new Db:</p><pre>// Existing DB:<br>&quot;OldDbContext&quot;: &quot;Server=ServerName;Initial Catalog=OldDatabaseName;Trusted_Connection=True;MultipleActiveResultSets=true;Encrypt=False;&quot;,<br><br>// New DB:<br>&quot;NewDbContext&quot;: &quot;Server=ServerName;Initial Catalog=NewDatabaseName;Trusted_Connection=True;MultipleActiveResultSets=true;Encrypt=False;&quot;</pre><h3>Step 1: Create a new Folder Structure</h3><p>You will need to <strong>create the following folder paths</strong> to accommodate the new DbContext and still keep the old one. As you will see, we need to do this separation by DbContext so the next steps are easier. And for maintainability :).</p><h3>Your Migrations Folder</h3><p><strong>Before:</strong></p><p>/Infrastructure/Migrations</p><p><strong>After:</strong></p><p>/Infrastructure/Migrations/NewMigrations</p><p>/Infrastructure/Migrations/OldMigrations <strong>NB:</strong> Move all old migrations, and the old snapshot, here.</p><h3>Your Configurations Folder</h3><p><strong>Before:</strong></p><p>/Infrastructure/Persistence/Configurations</p><p><strong>After:</strong></p><p>/Infrastructure/Persistence/NewConfigurations</p><p>/Infrastructure/Persistence/OldConfigurations <strong>NB:</strong> Move all old Configurations here.</p><h3>Step 2: Create the New DbContext</h3><p>Inside your infrastructure/Persistence folder <strong>create a new DbContext</strong> (e.g. NewDbContext.cs). Set it up as if it’s the only DbContext you have to deal with, i.e. the usual way.</p><p>In the <strong>OnModelCreating</strong> override method <strong>replace this</strong>:</p><pre>modelbuilder.ApplyConfigurationsFromAssembly(typeof(NewDbContext).Assembly);</pre><p><strong>With the code below.</strong> Do this because you <strong>don’t want to apply all the configurations</strong> in this assembly, <strong>only the ones that apply to this NewDbContext.</strong> <strong>If you don’t already have the above line of code</strong> to replace then just add the following code to the OnModelCreating override method:</p><pre>string desiredNamespace = &quot;[YourProjectName].Infrastructure.Persistence.NewConfigurations&quot;;<br>var configurationTypes = typeof(NewDbContext).Assembly.GetTypes()<br>    .Where(t =&gt; <br>        t.Namespace != null &amp;&amp; t.Namespace.StartsWith(desiredNamespace) <br>        &amp;&amp; t.IsClass <br>        &amp;&amp; !t.IsAbstract<br>        &amp;&amp; t.GetInterfaces()<br>                .Any(i =&gt;<br>                    i.IsGenericType <br>                    &amp;&amp; i.GetGenericTypeDefinition() == typeof(IEntityTypeConfiguration&lt;&gt;))<br>                );<br><br>foreach (var configurationType in configurationTypes)<br>{<br>    dynamic configurationInstance = Activator.CreateInstance(configurationType);<br>    modelbuilder.ApplyConfiguration(configurationInstance);<br>}</pre><p><strong>NB:</strong> Replace [YourSolutionName] with the name of your solution.</p><p>The above code allows the NewDbContext to only ‘detect’ the tables that implement IEntityTypeConfiguration inside the [YourSolutionName]/Infrastructure/Persistence/NewConfigurations folder.</p><p>Follow this same process for the oldDbContext (OldDbContext) so that it behaves the same, otherwise, it will detect all your NewDb tables as well when creating a migration for your oldDbContext.</p><p><strong>NB:</strong> Because of the way that we’ve set this up, it is <strong>required</strong> for all future tables to have an explicit configuration file (implementing IEntityTypeConfigurtion&lt;&gt;) so that it can be detected in the <strong>onModelCreating</strong> method.</p><blockquote>I have a suspicion that there’s a better way to do this, where we don’t need to check if the configuration classes implement the IEntityTypeConfiguration interface. Let me know if you find a better way of doing this.</blockquote><h3>Step 3: Add the new DbContext as a Service</h3><p>Not sure if it’s necessary but I created a new DbContext using a different schema name. After adding the new Context you should have something like this:</p><pre>services.AddDbContext&lt;OldDbContext&gt;(options =&gt;<br>  options.UseSqlServer(configuration.GetConnectionString(&quot;OldDbContext&quot;),<br>    b =&gt; b.MigrationsHistoryTable(<br>      tableName: HistoryRepository.DefaultTableName,<br>      schema: &quot;dbo&quot;)<br>    )<br>);<br><br>services.AddDbContext&lt;NewDbContext&gt;(options =&gt;<br>  options.UseSqlServer(configuration.GetConnectionString(&quot;NewDbContext&quot;),<br>    b =&gt; b.MigrationsHistoryTable(<br>      tableName: HistoryRepository.DefaultTableName,<br>      schema: &quot;new&quot;)<br>    )<br>);</pre><p><strong>Note:</strong> I did find that changing the schema name, from the default ‘dbo’, made it so that I wouldn’t get the usual IntelliSense in Microsoft SQL Server Management Studio 18. I had to specify ‘new’ every time I wanted to write an SQL query. Let me know if you know why or how to fix this.</p><p>Don’t forget that you will be injecting these Contexts inside your Controllers and other Services, so add them to your Program.cs file (or wherever you’re registering your DBContext) as follows:</p><pre>services.AddTransient&lt;OldDbContext&gt;();<br>services.AddTransient&lt;NewDbContext&gt;();</pre><h3>Step 4: Create your ‘initial’ Migration</h3><p>Everything should be good to go, you can now add your initial migration for the NewDbContext. Then run the command that you might already be familiar with to create the migration:</p><pre>dotnet ef migrations add ‘Initial’ --project src\\YourProjectName.csproj</pre><p><strong>You should get an error similar to this:</strong></p><blockquote>More than one DbContext was found. Specify which one to use. Use the ‘-Context’ parameter for PowerShell commands and the ‘ — — context’ parameter for dotnet commands</blockquote><p>You just added a new context to an existing assembly, so the <strong>compiler doesn’t know which context you are referring to</strong>. Try adding the context:</p><pre>dotnet ef migrations add ‘Initial’ --project src\\YourProjectName.csproj --context NewDbContext</pre><p>At the time of writing this, I didn’t get an error, but I’m aware that <strong>it could throw an error</strong> because it doesn’t know where to create this new migration. Or it might create a new migrations folder, which we don’t want. So instead we have to <strong>specify the output directory explicitly</strong> for the migration. So:</p><pre>dotnet ef migrations add &quot;Initial&quot; --project src\\YourProjectName.csproj -o &quot;Infrastructure/Migrations/NewMigrations&quot; --context NewDbContext</pre><h3>Step 5: Create the new Database</h3><p>You might face similar issues as in step 4 if you use the “old” way of creating/updating your new database, so instead run the following:</p><pre>dotnet ef database update --project src\\YourProjectName.csproj --context NewDbContext</pre><h4>Great, we’re done :)</h4><p><strong>For reference</strong>, here are the rest of the commands for managing migrations from here on out:</p><h3>OldDb Migrations:</h3><h4>Add a New Migration:</h4><pre>dotnet ef migrations add &quot;Initial&quot; --project src\YourProjectName.csproj -o &quot;Infrastructure/Migrations/OldMigrations&quot; --context OldDbContext</pre><h4>Update Database:</h4><pre>dotnet ef database update --project src\YourProjectName.csproj --context OldDbContext</pre><h4>Remove Last Migration:</h4><pre>dotnet ef migrations remove --project src\YourProjectName.csproj --context OldDbContext</pre><h3>NewDb Migrations:</h3><h4>Add a Migration:</h4><pre>dotnet ef migrations add &quot;Initial&quot; --project src\YourProjectName.csproj -o &quot;Infrastructure/Migrations/NewMigrations&quot; --context NewDbContext</pre><h4>Update Database:</h4><pre>dotnet ef database update --project src\YourProjectName.csproj --context NewDbContext</pre><h4>Remove Last Migration:</h4><pre>dotnet ef migrations remove --project src\YourProjectName.csproj --context NewDbContext</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b17b1a96e11c" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>