Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 774
Jamil Avatar asked Oct 17 '22 08:10

Jamil


1 Answers

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");
like image 141
Jammer Avatar answered Oct 21 '22 00:10

Jammer