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?
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");
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With