Add an implementation of 'IDesignTimeDbContextFactory<ServicesDbContext>' to the project error while creating a migration step in .NET core 2.0

妖精的绣舞 提交于 2019-11-30 21:25:30
Pascal

Sample:

public class ApplicationDbContext : IdentityDbContext
{
    public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options) : base(options) { }
}

public class ApplicationContextDbFactory : IDesignTimeDbContextFactory<ApplicationDbContext>
{
    ApplicationDbContext IDesignTimeDbContextFactory<ApplicationDbContext>.CreateDbContext(string[] args)
    {
        var optionsBuilder = new DbContextOptionsBuilder<ApplicationDbContext>();
        optionsBuilder.UseSqlServer<ApplicationDbContext>("Server = (localdb)\\mssqllocaldb; Database = MyDatabaseName; Trusted_Connection = True; MultipleActiveResultSets = true");

        return new ApplicationDbContext(optionsBuilder.Options);
    }
}

Location:

Put that class where the ApplicationDbContext is put. It will then be automatically picked up when you use dotnet ef cli commands.

A possible solution to IDesignTimeDbContextFactory<> problem is the DBContext discovery/launch during the add-migration process. Add migrations needs to get a context. If it cant, this error is thrown. This can happen if you do not have a public parameter-less DBContext. So a solution is to Add a public Parameter-less constructor to your context.

public  class SomeDbContext: DbContext
{
    // this PUBLIC constructor  is required for Migration tool
    public SomeDbContext()
    {

    }
  // the model...
    public DbSet<PocoBla> PocoBlas { get; set; }
    ....
 }

You can have a special version of your DBContext in a separate project .netCore console project for migration code generation purposes.

I solve the problem by simply updating Program.cs to the latest .NET Core 2.x pattern:

From 1.x:

using System.IO; using Microsoft.AspNetCore.Hosting;

namespace AspNetCoreDotNetCore1App {
    public class Program
    {
        public static void Main(string[] args)
        {
            var host = new WebHostBuilder()
                .UseKestrel()
                .UseContentRoot(Directory.GetCurrentDirectory())
                .UseIISIntegration()
                .UseStartup<Startup>()
                .UseApplicationInsights()
                .Build();

            host.Run();
        }
    } }

To 2.x:

using Microsoft.AspNetCore;
using Microsoft.AspNetCore.Hosting;

namespace AspNetCoreDotNetCore2App
{
    public class Program
    {
        public static void Main(string[] args)
        {
            BuildWebHost(args).Run();
        }

        public static IWebHost BuildWebHost(string[] args) =>
            WebHost.CreateDefaultBuilder(args)
                .UseStartup<Startup>()
                .Build();
    }
}

Source: https://docs.microsoft.com/en-us/ef/core/miscellaneous/cli/dbcontext-creation

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!