Entity Framework Core - 未找到设计时服务

sco*_*ter 6 c# entity-framework-core

我有一个非常基本的迁移文件。我dotnet ef database update --verbose在包管理器控制台窗口中执行,但在 SQL Server 中没有生成任何内容。

包管理器控制台窗口中的最后几行输出如下所示:

Finding design-time services for provider Microsoft.EntityFrameworkCore.SqlServer...
Using design-time services from provider Microsoft.EntityFrameworkCore.SqlServer.
Finding design-time services referenced by assembly BM.Server.
No referenced design-time services were found.
Finding IDesignTimeServices implementations in assembly BM.Server...
No design-time services were found.
Done.
Run Code Online (Sandbox Code Playgroud)

这是我的代码的样子,添加和删除迁移工作。它只是试图更新我遇到此问题的数据库。

public class Program
{
    public static void Main(string[] args)
    {
        CreateHostBuilder(args).Build().Run();
    }

    public static IHostBuilder CreateHostBuilder(string[] args) =>
        Host.CreateDefaultBuilder(args)
            .ConfigureWebHostDefaults(webBuilder =>
            {
                webBuilder.UseStartup<Startup>();
            });
}

public class Startup
{
    public void ConfigureServices(IServiceCollection services)
    {
        services.AddDbContext<BMDbContext>(options => options.UseSqlServer(Configuration.GetConnectionString("BMDbConnectionString")));
    }
}

public class BMDbContext : DbContext
{
    public BMDbContext(DbContextOptions<BMDbContext> options) : base(options) { }
}
Run Code Online (Sandbox Code Playgroud)

我还为项目安装了以下 nuget 包,两个 dll 都在我的 bin 目录中:Microsoft.EntityFrameworkCore.SqlServer Microsoft.EntityFrameworkCore.Design

小智 5

本文所述,您应该添加设计时 DbContext。将以下类添加到您的项目中:

using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Design;

namespace WebApplication8
{
    public class DesignTimeBMDbContext : IDesignTimeDbContextFactory<BMDbContext>
    {
        public BMDbContext CreateDbContext(string[] args)
        {
            var optionsBuilder = new DbContextOptionsBuilder<BMDbContext>();
            // pass your design time connection string here
            optionsBuilder.UseSqlServer("<connection_string>");
            return new BMDbContext(optionsBuilder.Options);
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

添加此类后,EF CLI 将使用它进行设计时数据库的创建和更新