3

EntityFramework Core – Add an implementation of IDesignTimeDbContextFactory – Multiple DbContext’s

Introduction

We already talked about problem when Entity Framework Core tooling requires you to implement IDesignTimeDbContextFactory<DbContext> – check out this post.

It gets interesting when you have more than one DbContext in your application and you want to add another implementation of IDesignTimeDbContextFactory, without repeating the code and making sure that EF Core tooling picks the right one.

 

Problem

We have more than DbContext  in Database project and we need an implementation of IDesignTimeDbContextFactory<DbContext>.

First DbContext:

Second DbContext:

If we try to add migrations from Database project:

We get the following error:

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.

If we specify the context:

Now we get this message:

Unable to create an object of type ‘OtherDbContext’. Add an implementation of ‘IDesignTimeDbContextFactory’ to the project, or see https://go.microsoft.com/fwlink/?linkid=851728 for additional patterns supported at design time.

 

Solution

Previously, for one DbContext and one implementation of IDesignTimeDbContextFactory<DbContext> we had this code:

One of the things we can do is to make this class and method generic and make two classes that will inherit this class.

One way to do generic implementation of DesignTimeDbContextFactory and CreateDbContext:

Now we can have two separate DesignTimeDbContextFactory implementations:

Now we can run the following command:

 

Share now!
Ibrahim Šuta
 

  • Pingback: The Morning Brew - Chris Alcock » The Morning Brew #2427()

  • Bravo Prochu

    “post on time” ! Thx !!! But how to add IHostingEnvironemt env to use something like
    .AddJsonFile($”appsettings.{env.EnvironemntName}.json”, optional: true, reloadOnChange: true)
    ..and second:
    defaultConnectionString has name for context; i have to pass it too;
    I tried with parameteres contructor but didn’t work;

    best regards
    bp

    • Sorry for late reply, just saw this.
      To get environment name you can use this: Environment.GetEnvironmentVariable(“ASPNETCORE_ENVIRONMENT”).