升级到 ASP.NET Core 2.0 后无法创建迁移 [英] Unable to create migrations after upgrading to ASP.NET Core 2.0
问题描述
升级到 ASP.NET Core 2.0 后,我似乎无法再创建迁移.
After upgrading to ASP.NET Core 2.0, I can't seem to create migrations anymore.
我要了
在类上调用方法BuildWebHost"时发生错误'程序'.在没有应用程序服务提供商的情况下继续.错误:发生了一个或多个错误.(无法打开数据库..."请求登录.登录失败.用户 '...' 登录失败"
"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 '...'"
和
无法创建'MyContext'类型的对象.添加一个实现'IDesignTimeDbContextFactory' 到项目,或参见https://go.microsoft.com/fwlink/?linkid=851728 了解更多模式在设计时支持."
"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 的项目/文件夹).
The command I previously ran was $ dotnet ef migrations add InitialCreate --startup-project "..Web"
(from the project/folder with the DBContext).
连接字符串:"Server=(localdb)\mssqllocaldb;Database=database;Trusted_Connection=True;MultipleActiveResultSets=true"
这是我的 Program.cs
This is my 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 的类.
You can add a class that implements IDesignTimeDbContextFactory inside of your Web project.
这是示例代码:
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);
}
}
然后,导航到您的数据库项目并从命令行运行以下命令:
Then, navigate to your Database project and run the following from command line:
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.
这篇关于升级到 ASP.NET Core 2.0 后无法创建迁移的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!