25

I have ASP.NET Core 1.1 project, which I'm trying to convert to v2.1. I've found IDesignTimeDbContextFactory implementation, but I don't understand where I should create the instance of this factory and how to use it for migrations normal working. Now before create/remove migration I must clean and rebuild solution, because if not, I will get this message: Unable to create an object of type 'MyDbContext'. Add an implementation of 'IDesignTimeDbContextFactory<MyDbContext>' to the project, or see https://go.microsoft.com/fwlink/?linkid=851728 for additional patterns supported at design time. All context data is in separated project. How to use IDesignTimeDbContextFactory implementation or what am I doing wrong?

Vitaliy
  • 645
  • 1
  • 10
  • 21

1 Answers1

37

Add this class to folder where you have your DbContext.

public class MyDbContextFactory : IDesignTimeDbContextFactory<MyDbContext>
    {      

        MyDbContext IDesignTimeDbContextFactory<MyDbContext>.CreateDbContext(string[] args)
        {
            IConfigurationRoot configuration = new ConfigurationBuilder()
                .SetBasePath(Directory.GetCurrentDirectory())
                .AddJsonFile("appsettings.json")
                .Build();

            var builder = new DbContextOptionsBuilder<MyDbContext>();
            var connectionString = configuration.GetConnectionString("DefaultConnection");

            builder.UseSqlServer(connectionString);

            return new MyDbContext(builder.Options);
        }
    }
Arayn
  • 986
  • 1
  • 16
  • 24
  • Thanks, looks like the problem was in different projects and namespaces of MyDbContextFactory and MyDbContext – Vitaliy Sep 26 '18 at 14:44
  • 1
    Nice! Just what I was looking for. – snapper Dec 10 '18 at 00:35
  • According [the docs](https://learn.microsoft.com/en-us/ef/core/cli/dbcontext-creation?tabs=dotnet-core-cli#from-a-design-time-factory), this class can be added to the startup project as well. – derekbaker783 May 19 '21 at 16:18
  • @derekbaker783 designtime builder is for design time purposes. startup registeration is for runtime. – Ali.Rashidi Dec 11 '22 at 06:23