【发布时间】:2017-04-23 17:24:30
【问题描述】:
我有一个 asp.net 核心项目,它需要能够在运行时支持插件,因此,我需要根据已插入的内容生成数据库表。每个插件都分为单独的项目和他们有自己的 DbContext 类。要使用的插件在编译时是未知的,只有在运行时才知道。
现在在 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”,但也没有用。
【问题讨论】:
-
我也在创建一个带有插件的项目,并且需要在运行时创建表 - EF 迁移不是一个选项。你找到解决办法了吗?
-
@Matt 很遗憾,没有。我只需要为我的项目使用不同的数据库来解决不同的插件。
-
我找到了一个解决方案,并将其作为答案发布在下面。祝你好运
标签: c# asp.net entity-framework