ef core trouble with creating schemas

asp.net-core c# entity-framework entity-framework-core

Question

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?

1
1
1/14/2019 10:58:08 AM

Accepted Answer

You are creating the same table, so ef detects that you already have it and it won't allow you to have duplicate.

0
1/14/2019 10:53:32 AM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow