今天在完成ASP .NET Core+Angular5项目的时候,更新了Model,把原有的数据库删除了,之后进行数据库迁移时一直发生异常,提示如下:
Entity Framework Core 2.0.1-rtm-125 initialized 'ApplicationDbContext' using provider 'Microsoft.EntityFrameworkCore.SqlServer' with options: None
和
An error occurred while calling method 'BuildWebHost' on class 'Program'. Continuing without the application service provider. Error: Cannot open database "DB_OnlineShoppingSystem" requested by the login. The login failed. Login failed for user
最后解决方法如下:
1、打开Startup.cs
文件并删除(或注释掉)以下行:
// Create a service scope to get an ApplicationDbContext instance using DI
using (var serviceScope =
app.ApplicationServices.GetRequiredService<IServiceScopeFactory>().CreateScope())
{
var dbContext = serviceScope.ServiceProvider.GetService<ApplicationDbContext>();
// Create the Db if it doesn't exist and applies any pending migration.
dbContext.Database.Migrate();
// Seed the Db.
DbSeeder.Seed(dbContext);
}
2、
打开
Program.cs
并替换此代码:
public static void Main(string[] args)
{
BuildWebHost(args).Run();
}
与此代码:
using Microsoft.Extensions.DependencyInjection;
public static void Main(string[] args)
{
var host = BuildWebHost(args);
using (var scope = host.Services.CreateScope())
{
var dbContext = scope.ServiceProvider.GetService<ApplicationDbContext>();
DbSeeder.Seed(dbContext);
}
host.Run();
}
3、打开命令提示符并浏览项目的根目录
4、键入以下命令:
dotnet ef migrations add "Initial" -o "Data\Migrations"
dotnet ef database update
附上解决方法链接:https://github.com/PacktPublishing/ASP.NET-Core-2-and-Angular-5/issues/4
备查!