私は実行時にプラグインをサポートする必要があるasp.netコアプロジェクトを持っており、プラグインされたものに基づいてデータベーステーブルを生成する必要がありますプラグインはそれぞれ別々のプロジェクトに分割され、独自のDbContextクラスを持っています。使用するプラグインは、実行時にのみコンパイル時にはわかりません。EFコア - ランタイム中にデータベースに新しいテーブルを追加
EFコアでは、既存のデータベースにテーブルを追加するだけの "UpdateDatabase"のようなメソッドがあると思っていましたが、間違っていました。これを達成する方法はありますか?私はプラグインごとに別々のデータベースを生成することができましたが、それは私が心に留めていたものではありません。一つのデータベースにすべてのテーブルが必要でした。ここで
は "HRContext" プラグインのコードです:ここで
using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.EntityFrameworkCore;
using Plugins.HR.Models.Entities;
namespace Plugins.HR.Contexts
{
public class HrContext : DbContext
{
public HrContext()
{
}
public HrContext(DbContextOptions<HrContext> contextOptions) : base(contextOptions)
{
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.HasDefaultSchema("HR");
base.OnModelCreating(modelBuilder);
}
public DbSet<Address> Address { get; set; }
public DbSet<Attendance> Attendance { get; set; }
public DbSet<Department> Departments { get; set; }
public DbSet<Employee> Employees { get; set; }
public DbSet<JobTitle> JobTitles { get; set; }
}
}
は "CoreContext" プラグインのコードの別の部分があります:Startup.csで
using System;
using System.Collections.Generic;
using System.Text;
using Core.Data.Models;
using Microsoft.EntityFrameworkCore;
namespace Core.Data.Contexts
{
public class CoreContext : DbContext
{
public CoreContext()
{
}
public CoreContext(DbContextOptions<CoreContext> contextOptions) : base(contextOptions)
{
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.HasDefaultSchema("Core");
base.OnModelCreating(modelBuilder);
}
public DbSet<Test> Tests { get; set; }
}
}
マイConfigureServices方法:
public void ConfigureServices(IServiceCollection services)
{
services.AddDbContext<CoreContext>(options => options.UseSqlServer("Data source = localhost; initial catalog = Company.Core; integrated security = true;"))
.AddDbContext<HrContext>(options => options.UseSqlServer("Data source = localhost; initial catalog = Company.HR; integrated security = true;"));
// Add framework services.
services.AddMvc();
}
接続文字列を同じに変更しようとすると、遅かれ早かれ1つのプラグインのテーブルが存在しないことを示すエラーです。私は "EnsureCreated"を試みましたが、それもうまくいきませんでした。
私もプラグインを使用してプロジェクトを作成し、実行時にテーブルを作成する必要がありますよ - EFの移行にオプションではありません。あなたは解決策を見つけましたか? – Matt
@Matt悲しいことに、私はちょうど私のプロジェクトのための異なったプラグインのための異なったデータベースと解決しなければならなかった。 – chelem7
私は解決策を見つけました。私は以下の答えとしてそれを投稿しました。がんばろう – Matt