我开始使用EF Core 2.0,我有一个针对.NET 4.6.1的控制台应用程序,我有一个非常简单的模型类,并且具有以下上下文:
public class ContextCore : DbContext
{
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
optionsBuilder.UseSqlServer(ConfigurationManager.ConnectionStrings["efCoreCon"].ConnectionString);
}
public DbSet<ModelC> Models { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
这是连接字符串:
<add name="efCoreCon" connectionString="server=PC-MSHWF\SQLEXPRESS;database=efCoreDB;integrated security=true;" />
Run Code Online (Sandbox Code Playgroud)
我注意到官方文档Enable-Migrations中的ef core中没有命令
所以我跑了,Add-migration firstMigration
但出现了这个错误:
在程序集“ NewConsole”中找不到迁移配置类型。(在Visual Studio中,您可以使用Package Manager控制台中的Enable-Migrations命令来添加迁移配置)。
当我尝试Enable-Migrations时,出现以下错误:
在程序集“ NewConsole”中找不到上下文类型。
在 powershell CLI 中输入 --> dotnet ef migrations add InitialMigration
这将安装正确的核心工具
// Package Manger
PM> Install-Package Microsoft.EntityFrameworkCore.Tools -Version 2.0.1
// or this will work inside the CLI Console
dotnet add package Microsoft.EntityFrameworkCore.Tools --version 2.0.1
// **for the current/LATEST ver. leave out version option it will install latest Install-Package Microsoft.EntityFrameworkCore.Tools
Run Code Online (Sandbox Code Playgroud)
修复您的错误问题:
看看这个答案:“你应该只需要更新你的project.json文件的工具部分来包含这个:”
"Microsoft.EntityFrameworkCore.Tools": {
"version": "2.0.1", // I corrected this from previous answer for your version
"imports": [
"portable-net45+win8+dnxcore50",
"portable-net45+win8"
]
}
Run Code Online (Sandbox Code Playgroud)
奖励 :)自动运行迁移......在主应用程序的startup.cs中。
// setup the HTTP request pipeline to check and migrate.
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
try
{
using (var migrationSvcScope = app.ApplicationServices.GetRequiredService<IServiceScopeFactory>()
.CreateScope())
{
migrationSvcScope.ServiceProvider.GetService<EFMigrationsMyDBContext>().Database.Migrate();
// you can also add the data here... let me know if you need I will post it
}
}
... // Rest of the startup stuff
}
Run Code Online (Sandbox Code Playgroud)
小智 5
转至Package Manager控制台,并使用安装所需的工具Install-Package Microsoft.EntityFrameworkCore.Tools。完成后,请尝试使用命令EntityFrameworkCore\Add-Migration firstMigration。