我需要在运行时中创建架构并在其中复制现有表。 DbContext:
public class TenantContext : DbContext
{
public TenantContext(string schemaName)
{
this.SchemaName = schemaName;
}
public string SchemaName { get; set; }
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
base.OnConfiguring(optionsBuilder);
optionsBuilder
.UseSqlServer("connString");
}
public virtual DbSet<TestEntity> TestEntities { get; set; }
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
modelBuilder.Entity<TestEntity>().ToTable("TestEntity", SchemaName);
}
}
架构创建:
public void CreateSchema(SchemaRequest req)
{
TenantContext context = new TenantContext(req.Name);
RelationalDatabaseCreator creator =
(RelationalDatabaseCreator) context.Database.GetService<IRelationalDatabaseCreator>();
creator.CreateTables();
}
当我尝试对其进行测试时,我创建了“ schema1.TestEntity”,而当我尝试创建“ schema2.TestEntity”时,它给了我System.Data.SqlClient.SqlException: 'There is already an object named 'TestEntity' in the database.'
Howewer,当我重新启动应用程序并再次尝试创建“ schema2.TestEntity”时,它运行良好,但在尝试创建第三个架构时却出现了相同的错误。我在做什么错了?
答案 0 :(得分:0)
您正在创建同一张表,因此ef检测到您已经拥有它,并且不允许您重复。