How to implement schema-per-tenant in EF core?

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

Question

I found many similar questions and posts how to do it, but I'm not sure which approach is better. I think that I need some DbContextFactory class which will return me context depending on the TenantId, but I don't know how to achieve this with OnModelCreating. I mostly saw posts about db-per-tenant architecture, and I'm not sure that I know how to bound schema to context(via user?). I tried to follow this https://romiller.com/2011/05/23/ef-4-1-multi-tenant-with-code-first/ but looks like this is not suitable for latest EF version. I also checked this Multi-Tenant With Code First EF6 but IDbModelCacheKeyProvider changed and now requires DbContext in Create, opposite to what I want to do. Can you please give me example of how this is done?

1
5
1/14/2019 7:50:45 AM

Accepted Answer

Use this code to set a default schema in your context:

protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder.HasDefaultSchema("blogging");
    }

Create another context using the same connection string and then do:

protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder.HasDefaultSchema("mydifferentschemaname");
    }

This shoud achieve what you desire.

There is more info here.

You can also map tables (entities) to schemas like:

modelBuilder.Entity<Department>().ToTable("t_Department", "school");
3
1/14/2019 8:38:23 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