I need to create schemas in the runtime and copy existing tables there. 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);
}
}
Schema creation:
public void CreateSchema(SchemaRequest req)
{
TenantContext context = new TenantContext(req.Name);
RelationalDatabaseCreator creator =
(RelationalDatabaseCreator) context.Database.GetService<IRelationalDatabaseCreator>();
creator.CreateTables();
}
When I tried to test it, I created "schema1.TestEntity", and when I tried to create "schema2.TestEntity", it gave me System.Data.SqlClient.SqlException: 'There is already an object named 'TestEntity' in the database.'
Howewer, when I restarted the app and once again tried to create "schema2.TestEntity", it worked fine, but gave same error when I tried to create third schema. What am I doing wrong?
You are creating the same table, so ef detects that you already have it and it won't allow you to have duplicate.