升级到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屋!