web-dev-qa-db-ja.com

EFコアで移行を有効にしますか?

私はEF Core 2.0を使い始めています。NET4.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;" />

公式ドキュメント のefコアにEnable-Migrationsのコマンドがないことに気づきました

Add-migration firstMigrationを実行しましたが、次のエラーが発生しました:

アセンブリ 'NewConsole'に移行構成タイプが見つかりませんでした。 (Visual Studioでは、パッケージマネージャーコンソールからEnable-Migrationsコマンドを使用して、移行構成を追加できます)。

enable-Migrationsを試したところ、次のエラーが発生しました。

アセンブリ 'NewConsole'でコンテキストタイプが見つかりませんでした。

8
mshwf

パッケージマネージャーコンソールに移動し、Install-Package Microsoft.EntityFrameworkCore.Toolsを使用して必要なツールをインストールします。完了したら、コマンドEntityFrameworkCore\Add-Migration firstMigrationを使用してみてください。

10
Stivi C.

powerShell CLIでこれを入力-> dotnet ef migrations add InitialMigration

これにより、移行が可能になります。 enter image description here


正しいコアツール がインストールされます

// 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 : "project.jsonファイルのtoolsセクションを更新して、これを含める必要があります:"

"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
}
2
transformer

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 <<migration's_name>>。例えば: dotnet ef migrations add Init。スタートアッププロジェクトが別のフォルダーにある場合は、--startup-project ../<<other_project_folder>>
1
Pyotreq

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 = "[email protected]" },
          password: "1234");
      }
    }

    //now run
    Host.Run();
  }

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