在EF核心中启用迁移?

时间:2017-12-01 17:49:37

标签: c# ef-core-2.0

我开始使用EF Core 2.0, 我有一个针对.NET 4.6.1的控制台应用程序 我有一个非常简单的模型类,以及这个上下文:

Connectors::Scim::Preprocessors::Builder.
    should_receive(:build).
    with(
      hash_including(:connector => connector)
      ).
    and_return(preprocessor)
}

这是连接字符串:

 public class ContextCore : DbContext
    {

        protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
        {
            optionsBuilder.UseSqlServer(ConfigurationManager.ConnectionStrings["efCoreCon"].ConnectionString);
        }
        public DbSet<ModelC> Models { get; set; }
    }

我注意到official docs

在ef核心中没有<add name="efCoreCon" connectionString="server=PC-MSHWF\SQLEXPRESS;database=efCoreDB;integrated security=true;" /> 的命令

所以我运行Enable-Migrations 但是我收到了这个错误:

  

在程序集中未找到迁移配置类型   &#39; NewConsole&#39 ;. (在Visual Studio中,您可以使用“启用 - 迁移”   Package Manager控制台中的命令以添加迁移   配置)。

当我尝试启用迁移时,我收到此错误:

  

在程序集中找不到上下文类型&#39; NewConsole&#39;。

4 个答案:

答案 0 :(得分:2)

转到程序包管理器控制台并使用Install-Package Microsoft.EntityFrameworkCore.Tools安装所需的工具。完成后尝试使用命令EntityFrameworkCore\Add-Migration firstMigration

答案 1 :(得分:2)

使用C#7.1启动.NET Core 2,您可以对应用程序使用异步Main方法,因此可以在主机完成构建后立即在运行主机之前调用所有初始化逻辑:

public class Program
{
  public static async Task Main(string[] args)
  {
    //first build
    var host = CreateHostBuilder(args).Build();

    //initialize
    using (var serviceScope = host.Services.CreateScope())
    {
      var serviceProvider = serviceScope.ServiceProvider;
      var isDevelopment = 
        serviceProvider.GetRequiredService<IWebHostEnvironment>().IsDevelopment();

      using var context = serviceProvider.GetRequiredService<AppDbContext>();


      if (isDevelopment)
        await context.Database.EnsureCreatedAsync();
      else
        await context.Database.MigrateAsync();

      if (isDevelopment)
      {
        using var userManager = 
          serviceProvider.GetRequiredService<UserManager<AppUser>>();
        await userManager
          .CreateAsync(new AppUser { UserName = "dummy", Email = "dummy@dumail.com" },
          password: "1234");
      }
    }

    //now run
    host.Run();
  }

  public static IHostBuilder CreateHostBuilder(string[] args) =>
    Host.CreateDefaultBuilder(args)
      .ConfigureWebHostDefaults(webBuilder =>
      {
        webBuilder.UseStartup<Startup>();
      });
}

答案 2 :(得分:1)

在PowerShell CLI中输入

- &gt; dotnet ef migrations add InitialMigration

这可以启用迁移。enter image description here

这将安装correct core tools

// 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

enter image description here

修复您的错误问题:

看看这个SO answer:&#34;你应该只需要更新project.json文件的tools部分就可以包含这个:&#34;

"Microsoft.EntityFrameworkCore.Tools": {
  "version": "2.0.1",  // I corrected this from previous answer for your version
  "imports": [
    "portable-net45+win8+dnxcore50",
    "portable-net45+win8"
  ]
}

Bonus :)在主应用程序的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
}

答案 3 :(得分:1)

编辑您的.csproj,其中包含EF Core 2.0并添加:

<ItemGroup>
    <DotNetCliToolReference Include="Microsoft.EntityFrameworkCore.Tools.DotNet" Version="2.0.0" />
</ItemGroup>
  1. 打开Windows PowerShell
  2. 转到您拥有EF Core 2.0的目录
  3. 输入dotnet ef migrations add <<migration's_name>>。例如:dotnet ef migrations add Init。如果您的启动项目位于不同的文件夹中,则可以使用--startup-project ../<<other_project_folder>>