私は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'でコンテキストタイプが見つかりませんでした。
パッケージマネージャーコンソールに移動し、Install-Package Microsoft.EntityFrameworkCore.Tools
を使用して必要なツールをインストールします。完了したら、コマンドEntityFrameworkCore\Add-Migration firstMigration
を使用してみてください。
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
バグの問題を修正する:
これを見てください 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
}
EF Core 2.0がある.csprojを編集して、以下を追加します。
<ItemGroup>
<DotNetCliToolReference Include="Microsoft.EntityFrameworkCore.Tools.DotNet" Version="2.0.0" />
</ItemGroup>
dotnet ef migrations add <<migration's_name>>
。例えば: dotnet ef migrations add Init
。スタートアッププロジェクトが別のフォルダーにある場合は、--startup-project ../<<other_project_folder>>
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>();
});
}