我有一个asp.net core项目,需要能够在运行时支持插件,因此需要根据已插入的内容生成数据库表。这些插件分别分为不同的项目,并且它们都有自己的DbContext类。这些要使用的插件只有在运行时才知道,而不是在编译时。
现在在EF Core中,我认为应该有一种像“UpdateDatabase”这样的方法,可以向现有数据库中添加表,但我错了。有没有办法实现这个功能?我能够为每个插件生成单独的数据库,但那不是我所想要的..我需要所有的表都在一个数据库中。
以下是“HRContext”插件的代码:
现在在EF Core中,我认为应该有一种像“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”插件的另一段代码:
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; }
}
}
我在Startup.cs中有一个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();
}
如果我试图将连接字符串改为相同的,迟早会出现一个错误,显示一个插件的表不存在。我尝试使用“EnsureCreated”,但它也没有起作用。