【问题标题】:Enabling Migrations in EF core?在 EF 核心中启用迁移?
【发布时间】:2018-05-15 21:08:32
【问题描述】:

我开始使用 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; }
}

这是连接字符串:

<add name="efCoreCon" connectionString="server=PC-MSHWF\SQLEXPRESS;database=efCoreDB;integrated security=true;" />

我注意到 official docs 的 ef 核心中没有 Enable-Migrations 的命令

所以我运行Add-migration firstMigration 但我收到了这个错误:

在程序集中找不到迁移配置类型 '新控制台'。 (在 Visual Studio 中,您可以使用 Enable-Migrations 来自包管理器控制台的命令以添加迁移 配置)。

当我尝试 Enable-Migrations 时,我收到了这个错误:

在程序集“NewConsole”中找不到上下文类型。

【问题讨论】:

  • 您正在使用 EF 非核心命令。使用dotnet ef ...
  • 你的上下文的命名空间是什么?
  • @PabloTondolodeVargas NewConsole.EFCore
  • 我使用了dotnet ef migrations add InitialCreate,但得到: dotnet : No executable found matching command "dotnet-ef"...

标签: c# ef-core-2.0


【解决方案1】:

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

【讨论】:

  • 对我来说,只需安装软件包并重新启动 Visual Studio 就足以解决问题
【解决方案2】:

在 powershell CLI 中输入 --> dotnet ef migrations add InitialMigration

这将启用迁移。


这将安装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
// **for the current/LATEST ver. leave out version option it will install latest Install-Package Microsoft.EntityFrameworkCore.Tools 


修复您的错误问题:

看看这个SO answer:“你应该只需要更新你的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"
  ]
}

奖励 :)自动运行迁移...在您的主应用程序的 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】:

    在您拥有 EF Core 2.0 的位置编辑 .csproj 并添加:

    <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 &lt;&lt;migration's_name&gt;&gt;。例如:dotnet ef migrations add Init。如果您的启动项目在不同的文件夹中,那么您可以使用--startup-project ../&lt;&lt;other_project_folder&gt;&gt;

    【讨论】:

      【解决方案4】:

      使用 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>();
            });
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2016-10-13
        • 1970-01-01
        • 2018-05-21
        • 2018-08-09
        • 2019-06-18
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多