Skip to content

Schema-based multi-tenancy #9965

Open

Description

@ajcvickers

A common mutli-tenant scenario involves using model that only differs by schema. Currently this requires a different model for each tenant. If the model could be parameterized somehow so that the schema used is different depending on the context/connection/tenantid/etc, then this could allow the same model to be used for multiple tenants, which would also mean that needing to change the model cache key would not be needed. We should also consider how this interacts with reverse engineering and migrations. See #9864 for a particular case where this could be useful.

Activity

  1. added this to the Backlog milestone on Oct 4, 2017
  2. ste4net commented on Oct 9, 2017

    @ste4net

    This future will be really useful for us.
    I was using a multi-tenant configuration in ef core 1.x now i am trying to port it to ef core2 with truble because we were using a lot of workaround to do the job.
    In my scenario i have a lot of per-tenant tables and few tables (like User account) shared by all tenants.
    With a context factory class and a customized Context class i can build a context with only shared tables or a context with all tables (shared and perTanant) for the requested tenant .

    protected void CustomCreateModel(string tenantSchema, ModelBuilder builder, bool sharedOnly)
        {
            if (sharedOnly)
            {
                builder.Ignore<RoomPerUser>();
                builder.Entity<UserProfile>().Ignore(p => p.MyRooms);
            }
    
            base.OnModelCreating(builder); //CREATE MODEL FOR IdentityDbContext  
            builder.Entity<UserCompany>();
    
            if (!sharedOnly)
            {
                builder.Entity<RoomPerUser>().HasOne(r => r.UserProfile;
                [...]
            }
        }
    

    When the model is used by migration an IDbContextFactory read parameter "EnvironmentName" and create the full model or the shared_only depending on param value. This is a stupid workaround i have used to call AddMigration working with separate file for SharedOnly tables. In this way when migration create the Files i can create a sqlScript and use it in a loop for each tenant.

    When the model is used by the asp.net core application the IModel is compiled and cached in a concurrent dictionary with tenant code as the key. This was obviously to avoid to do the hardest compiling job for each instance of Context.

    public class DbOptionSetter : IDbOptionSetter
        {
    [..]
            public void SetDbContextOptionsBuilder(string tenant, bool sharedEntitiesOnly, DbContextOptionsBuilder optionsBuilder)
            {
                var cachedOptions = _optionsCache.GetOrAdd(tenant,
                                                            t =>
                                                            {
                                                                _logger.LogDebug(LoggingEvents.CREATE_NEW_IMODEL, "Create new IModel for tenant:[{1}]", tenant);
                                                                return MyContext.GetModel(tenant, sharedEntitiesOnly);
                                                            });
                optionsBuilder.UseModel(cachedOptions);
                optionsBuilder.UseSqlServer(ConnectionString, b => b.MigrationsAssembly(TMP_MIGRATION_ASSEBLY));
            }
        }
    

    This code was for ef core 1.x now i am porting it to ef core 2.0

    Thank you

  3. changed the title [-]Allow parts of model to be parameterized--e.g. schema[/-] [+]Schema-based multi-tenancy[/+] on Oct 20, 2022
  4. added theissue type on Jun 15, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Projects

    No projects

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions