c# - 升级到 ASP.NET Core 2.0 后无法创建迁移

标签 c# asp.net-core asp.net-core-mvc entity-framework-core asp.net-core-2.0

升级到 ASP.NET Core 2.0 后,我似乎无法再创建迁移。

我得到了

"An error occurred while calling method 'BuildWebHost' on class 'Program'. Continuing without the application service provider. Error: One or more errors occurred. (Cannot open database "..." requested by the login. The login failed. Login failed for user '...'"

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

我之前运行的命令是 $ dotnet ef migrations add InitialCreate --startup-project "..\Web"(来自具有 DBContext 的项目/文件夹)。

连接字符串:"Server=(localdb)\\mssqllocaldb;Database=database;Trusted_Connection=True;MultipleActiveResultSets=true"

这是我的 Program.cs

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

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

最佳答案

您可以在您的 Web 项目中添加一个实现 IDesignTimeDbContextFactory 的类。

示例代码如下:

public class DesignTimeDbContextFactory : IDesignTimeDbContextFactory<CodingBlastDbContext>
{
    public CodingBlastDbContext CreateDbContext(string[] args)
    {
        IConfigurationRoot configuration = new ConfigurationBuilder()
            .SetBasePath(Directory.GetCurrentDirectory())
            .AddJsonFile("appsettings.json")
            .Build();
        var builder = new DbContextOptionsBuilder<CodingBlastDbContext>();
        var connectionString = configuration.GetConnectionString("DefaultConnection");
        builder.UseSqlServer(connectionString);
        return new CodingBlastDbContext(builder.Options);
    }
}

然后,导航到您的数据库项目并从命令行运行以下命令:

dotnet ef migrations add InitialMigration -s ../Web/

dotnet ef database update -s ../Web/

-s stands for startup project and ../Web/ is the location of my web/startup project.

resource

关于c# - 升级到 ASP.NET Core 2.0 后无法创建迁移,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45782446/

相关文章:

c# - 如何在api项目的Startup类中使用集成测试项目的设置?

asp.net-mvc - VS 2015RC 中的 MVC 6 升级

visual-studio-2015 - 如何在 MVC 6 应用程序中启用 SSL?

c# - RhinoMocks - 未在 AssertWasCalled 中指定所有参数

c# - 向列表中添加多个变量

c# - 在 Linux 上的 c# 或 c++ 中修改文本文件并使用命令行参数执行程序

c# - 知道调用 List.Sort() 后顺序是否改变了吗?

asp.net-core - ASP.NET Core 和 OpenID 连接重定向到外部身份提供程序

c# - 删除 HTTP 服务器和 X-Powered-By header

c# - 为什么异常重定向到不同的页面?