43

UPD here is the way I solved the problem. Although it's likely to be not the best one, it worked for me.


I have an issue with working with EF Core. I want to separate data for different companies in my project's database via schema-mechanism. My question is how I can change the schema name in runtime? I've found similar question about this issue but it's still unanswered and I have some different conditions. So I have the Resolve method that grants the db-context when necessary

public static void Resolve(IServiceCollection services) {
    services.AddIdentity<ApplicationUser, IdentityRole>()
        .AddEntityFrameworkStores<DomainDbContext>()
        .AddDefaultTokenProviders();
    services.AddTransient<IOrderProvider, OrderProvider>();
    ...
}

I can set the schema-name in OnModelCreating, but, as was found before, this method is called just once, so I can set schema name globaly like that

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

or right in the model via an attribute

[Table("order", Schema = "public")]
public class Order{...}

But how can I change the schema name on runtime? I create the context per each request, but first I fugure out the schema-name of the user via a request to a schema-shared table in the database. So what is the right way to organize that mechanism:

  1. Figure out the schema name by the user credentials;
  2. Get user-specific data from database from specific schema.

Thank you.

P.S. I use PostgreSql and this is the reason for lowecased table names.

Ziga Petek
  • 3,953
  • 5
  • 33
  • 43
user3272018
  • 2,309
  • 5
  • 26
  • 48

11 Answers11

33

Did you already use EntityTypeConfiguration in EF6?

I think the solution would be use mapping for entities on OnModelCreating method in DbContext class, something like this:

using System;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata.Conventions.Internal;
using Microsoft.Extensions.Options;

namespace AdventureWorksAPI.Models
{
    public class AdventureWorksDbContext : Microsoft.EntityFrameworkCore.DbContext
    {
        public AdventureWorksDbContext(IOptions<AppSettings> appSettings)
        {
            ConnectionString = appSettings.Value.ConnectionString;
        }

        public String ConnectionString { get; }

        protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
        {
            optionsBuilder.UseSqlServer(ConnectionString);

            // this block forces map method invoke for each instance
            var builder = new ModelBuilder(new CoreConventionSetBuilder().CreateConventionSet());

            OnModelCreating(builder);

            optionsBuilder.UseModel(builder.Model);
        }

        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            modelBuilder.MapProduct();

            base.OnModelCreating(modelBuilder);
        }
    }
}

The code on OnConfiguring method forces the execution of MapProduct on each instance creation for DbContext class.

Definition of MapProduct method:

using System;
using Microsoft.EntityFrameworkCore;

namespace AdventureWorksAPI.Models
{
    public static class ProductMap
    {
        public static ModelBuilder MapProduct(this ModelBuilder modelBuilder, String schema)
        {
            var entity = modelBuilder.Entity<Product>();

            entity.ToTable("Product", schema);

            entity.HasKey(p => new { p.ProductID });

            entity.Property(p => p.ProductID).UseSqlServerIdentityColumn();

            return modelBuilder;
        }
    }
}

As you can see above, there is a line to set schema and name for table, you can send schema name for one constructor in DbContext or something like that.

Please don't use magic strings, you can create a class with all available schemas, for example:

using System;

public class Schemas
{
    public const String HumanResources = "HumanResources";
    public const String Production = "Production";
    public const String Sales = "Sales";
}

For create your DbContext with specific schema you can write this:

var humanResourcesDbContext = new AdventureWorksDbContext(Schemas.HumanResources);

var productionDbContext = new AdventureWorksDbContext(Schemas.Production);

Obviously you should to set schema name according schema's name parameter's value:

entity.ToTable("Product", schemaName);
granadaCoder
  • 26,328
  • 10
  • 113
  • 146
H. Herzl
  • 3,030
  • 1
  • 14
  • 19
  • 5
    As I wrote above, there is no issue with sitting schema name in `OnModelCreating`, problem is this method called just once, so next created context will have the same schema. But maybe I've missed something important in your reply? – user3272018 Sep 22 '16 at 07:07
  • I got your point, you're right my previous answer doesn't include the solution for OnModelCreating issue, but I've searched on blogs a solution for this issue and I found the code for OnConfiguring method, I modified my answer please check it and let me know if is useful [link](https://github.com/Grinderofl/FluentModelBuilder/issues/9) – H. Herzl Sep 22 '16 at 21:49
  • This may work for small projects but I cannot imagine maintaining the MapProduct method for hundreds of tables, not mentioning all possible settings and migrations... – Tomas Voracek Feb 01 '17 at 11:51
  • You have a good point, Are you talking about write code for those methods or maintaining a large code files? – H. Herzl Feb 02 '17 at 07:50
  • From what namespace AppSettings class is? thnk. – Kate May 31 '21 at 18:31
13

Define your context and pass the schema to the constructor.

In OnModelCreating Set the default schema.

   public class MyContext : DbContext , IDbContextSchema
    {
        private readonly string _connectionString;
        public string Schema {get;}

        public MyContext(string connectionString, string schema)
        {
            _connectionString = connectionString;
            Schema = schema;
        }

        protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
        {
            if (!optionsBuilder.IsConfigured)
            {
                optionsBuilder.ReplaceService<IModelCacheKeyFactory, DbSchemaAwareModelCacheKeyFactory>();
                optionsBuilder.UseSqlServer(_connectionString);
            }

            base.OnConfiguring(optionsBuilder);
        }

        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            modelBuilder.HasDefaultSchema(Schema);
            
            // ... model definition ...
        }
    }

Implement your IModelCacheKeyFactory.

public class DbSchemaAwareModelCacheKeyFactory : IModelCacheKeyFactory
    {
        
        public object Create(DbContext context)
        {
            return new {
                Type = context.GetType(),
                Schema = context is IDbContextSchema schema 
                    ? schema.Schema 
                    :  null
            };
        }
    }

In OnConfiguring replace the default implementation of IModelCacheKeyFactory with your custom implementation.

With the default implementation of IModelCacheKeyFactory the method OnModelCreating is executed only the first time the context is instantiated and then the result is cached. Changing the implementation you can modify how the result of OnModelCreating is cached and retrieve. Including the schema in the caching key you can get the OnModelCreating executed and cached for every different schema string passed to the context constructor.

// Get a context referring SCHEMA1
var context1 = new MyContext(connectionString, "SCHEMA1");
// Get another context referring SCHEMA2
var context2 = new MyContext(connectionString, "SCHEMA2");
Ghini Antonio
  • 2,992
  • 2
  • 25
  • 48
10

Sorry everybody, I should've posted my solution before, but for some reason I didn't, so here it is.

BUT

Keep in mind that anything could be wrong with the solution since it neither hasn't been reviewed by anybody nor production-proved, probably I'll get some feedback here.

In the project I used ASP .NET Core 1


About my db structure. I have 2 contexts. The first one contains information about users (including the db scheme they should address), the second one contains user-specific data.

In Startup.cs I add both contexts

public void ConfigureServices(IServiceCollection 
    services.AddEntityFrameworkNpgsql()
        .AddDbContext<SharedDbContext>(options =>
            options.UseNpgsql(Configuration["MasterConnection"]))
        .AddDbContext<DomainDbContext>((serviceProvider, options) => 
            options.UseNpgsql(Configuration["MasterConnection"])
                .UseInternalServiceProvider(serviceProvider));
...
    services.Replace(ServiceDescriptor.Singleton<IModelCacheKeyFactory, MultiTenantModelCacheKeyFactory>());
    services.TryAddSingleton<IHttpContextAccessor, HttpContextAccessor>();

Notice UseInternalServiceProvider part, it was suggested by Nero Sule with the following explanation

At the very end of EFC 1 release cycle, the EF team decided to remove EF's services from the default service collection (AddEntityFramework().AddDbContext()), which means that the services are resolved using EF's own service provider rather than the application service provider.

To force EF to use your application's service provider instead, you need to first add EF's services together with the data provider to your service collection, and then configure DBContext to use internal service provider

Now we need MultiTenantModelCacheKeyFactory

public class MultiTenantModelCacheKeyFactory : ModelCacheKeyFactory {
    private string _schemaName;
    public override object Create(DbContext context) {
        var dataContext = context as DomainDbContext;
        if(dataContext != null) {
            _schemaName = dataContext.SchemaName;
        }
        return new MultiTenantModelCacheKey(_schemaName, context);
    }
}

where DomainDbContext is the context with user-specific data

public class MultiTenantModelCacheKey : ModelCacheKey {
    private readonly string _schemaName;
    public MultiTenantModelCacheKey(string schemaName, DbContext context) : base(context) {
        _schemaName = schemaName;
    }
    public override int GetHashCode() {
        return _schemaName.GetHashCode();
    }
}

Also we have to slightly change the context itself to make it schema-aware:

public class DomainDbContext : IdentityDbContext<ApplicationUser> {
    public readonly string SchemaName;
    public DbSet<Foo> Foos{ get; set; }

    public DomainDbContext(ICompanyProvider companyProvider, DbContextOptions<DomainDbContext> options)
        : base(options) {
        SchemaName = companyProvider.GetSchemaName();
    }
    protected override void OnModelCreating(ModelBuilder modelBuilder) {
        modelBuilder.HasDefaultSchema(SchemaName);
        base.OnModelCreating(modelBuilder);
    }
}

and the shared context is strictly bound to shared schema:

public class SharedDbContext : IdentityDbContext<ApplicationUser> {
    private const string SharedSchemaName = "shared";
    public DbSet<Foo> Foos{ get; set; }
    public SharedDbContext(DbContextOptions<SharedDbContext> options)
        : base(options) {}
    protected override void OnModelCreating(ModelBuilder modelBuilder) {
        modelBuilder.HasDefaultSchema(SharedSchemaName);
        base.OnModelCreating(modelBuilder);
    }
}

ICompanyProvider is responsible for getting users schema name. And yes, I know how far from the perfect code it is.

public interface ICompanyProvider {
    string GetSchemaName();
}

public class CompanyProvider : ICompanyProvider {
    private readonly SharedDbContext _context;
    private readonly IHttpContextAccessor _accesor;
    private readonly UserManager<ApplicationUser> _userManager;

    public CompanyProvider(SharedDbContext context, IHttpContextAccessor accesor, UserManager<ApplicationUser> userManager) {
        _context = context;
        _accesor = accesor;
        _userManager = userManager;
    }
    public string GetSchemaName() {
        Task<ApplicationUser> getUserTask = null;
        Task.Run(() => {
            getUserTask = _userManager.GetUserAsync(_accesor.HttpContext?.User);
        }).Wait();
        var user = getUserTask.Result;
        if(user == null) {
            return "shared";
        }
        return _context.Companies.Single(c => c.Id == user.CompanyId).SchemaName;
    }
}

And if I haven't missed anything, that's it. Now in every request by an authenticated user the proper context will be used.

I hope it helps.

Community
  • 1
  • 1
user3272018
  • 2,309
  • 5
  • 26
  • 48
  • 2
    You set the DefaultSchema during OnModelCreating... but that method is only called once. So how are you changing the schema on the fly per request? I don't see how this solution works. – Jarrich Van de Voorde Jun 08 '18 at 06:01
  • @JarrichVandeVoorde, the model is cached internally by EF, but in this case, MultiTenantModelCacheKeyFactory configure EF and the cache is splited according to the current company (or the schema associated to the current company). When the dbcontext is instancied, the key is different, then the OnModelCreating will be called again if not found in the cache. The negative aspect of this method is the cache is grow up for each new company (in my case it's a cause of memory overflow exception) – t.ouvre Oct 10 '19 at 12:20
  • @user3272018, Thank you very much. This is an awesome idea. My scenario is to create schema onfly and reload mapping. a. I was looking into ModelSource and tried to clear the cache in the ModelSource. But changing the Cache Key is a much easier way :) b. UseInternalServiceProvider() is great, which solves the problem that in EF Core, ServiceProvider will be initialized during DbContext is being initializing. – Robin Ding Dec 12 '19 at 16:00
5

There are a couple ways to do this:

  • Build the model externally and pass it in via DbContextOptionsBuilder.UseModel()
  • Replace the IModelCacheKeyFactory service with one that takes the schema into account
bricelam
  • 28,825
  • 9
  • 92
  • 117
  • 4
    Could you please provide some details or links to some documentation/blogs/tutorials? – user3272018 Sep 15 '16 at 17:35
  • @user3272018 I have same problem, there is no documentation or samples how to implement IModelCacheKeyFactory in EF Core properly. – Tomas Voracek Feb 01 '17 at 11:28
  • 1
    @tomas-voracek Oh, eventually I did it. I will provide that code as self-answer a little bit later. I'm sure it's not a perfect way to reach my goal, but it works. Maybe even someone could improve my solution. Sorry for I didn't do it earlier. – user3272018 Feb 01 '17 at 12:21
  • Hi @user3272018 can you share your solution with us ? I`m trying to accomplish the same thing. – Diego Garcia Jul 15 '18 at 21:49
  • 1
    @Diego, as I mentioned in the question I already did share my solution [here](https://stackoverflow.com/questions/39499470/dynamically-changing-schema-in-entity-framework-core/50529432#50529432) – user3272018 Jul 16 '18 at 16:52
  • @user3272018 thanks I`ve just has to change some minor things but its working nice ;) – Diego Garcia Jul 16 '18 at 19:25
  • @user3272018 similar to yours solution https://stackoverflow.com/questions/37180426/how-to-change-database-schema-on-runtime-in-ef7-or-ef-core/52721650#52721650 – Serhii Kyslyi Oct 09 '18 at 13:08
5

Took several hours to figure this out with EFCore. Seems to be alot of confusion on the proper way of implementing this. I believe the simple and correct way of handling custom models in EFCore is replacing the default IModelCacheKeyFactory service like I show below. In my example I am setting custom table names.

  1. Create a ModelCacheKey variable in your context class.
  2. In your context constructor, set the ModelCacheKey variable
  3. Create a class that inherits from IModelCacheKeyFactory and use ModelCacheKey (MyModelCacheKeyFactory)
  4. In OnConfiguring method (MyContext), replace the default IModelCacheKeyFactory
  5. In OnModelCreating method (MyContext), use the ModelBuilder to define whatever you need.
public class MyModelCacheKeyFactory : IModelCacheKeyFactory
{
    public object Create(DbContext context)
        => context is MyContext myContext ?
        (context.GetType(), myContext.ModelCacheKey) :
        (object)context.GetType();
}

public partial class MyContext : DbContext
{
     public string Company { get; }
     public string ModelCacheKey { get; }
     public MyContext(string connectionString, string company) : base(connectionString) 
     { 
         Company = company;
         ModelCacheKey = company; //the identifier for the model this instance will use
     }

     protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
     {
         //This will create one model cache per key
         optionsBuilder.ReplaceService<IModelCacheKeyFactory, MyModelCacheKeyFactory();
     }

     protected override void OnModelCreating(ModelBuilder modelBuilder)
     {
         modelBuilder.Entity<Order>(entity => 
         { 
             //regular entity mapping 
         });

         SetCustomConfigurations(modelBuilder);
     }

     public void SetCustomConfigurations(ModelBuilder modelBuilder)
     {
         //Here you will set the schema. 
         //In my example I am setting custom table name Order_CompanyX

         var entityType = typeof(Order);
         var tableName = entityType.Name + "_" + this.Company;
         var mutableEntityType = modelBuilder.Model.GetOrAddEntityType(entityType);
         mutableEntityType.RemoveAnnotation("Relational:TableName");
         mutableEntityType.AddAnnotation("Relational:TableName", tableName);
     }
}

The result is each instance of your context will cause efcore to cache based on the ModelCacheKey variable.

C Rudolph
  • 522
  • 7
  • 6
3

I find this blog might be useful for you. Perfect !:)

https://romiller.com/2011/05/23/ef-4-1-multi-tenant-with-code-first/

This blog is based on ef4, I'm not sure whether it will work fine with ef core.

public class ContactContext : DbContext
{
    private ContactContext(DbConnection connection, DbCompiledModel model)
        : base(connection, model, contextOwnsConnection: false)
    { }

    public DbSet<Person> People { get; set; }
    public DbSet<ContactInfo> ContactInfo { get; set; }

    private static ConcurrentDictionary<Tuple<string, string>, DbCompiledModel> modelCache
        = new ConcurrentDictionary<Tuple<string, string>, DbCompiledModel>();

    /// <summary>
    /// Creates a context that will access the specified tenant
    /// </summary>
    public static ContactContext Create(string tenantSchema, DbConnection connection)
    {
        var compiledModel = modelCache.GetOrAdd(
            Tuple.Create(connection.ConnectionString, tenantSchema),
            t =>
            {
                var builder = new DbModelBuilder();
                builder.Conventions.Remove<IncludeMetadataConvention>();
                builder.Entity<Person>().ToTable("Person", tenantSchema);
                builder.Entity<ContactInfo>().ToTable("ContactInfo", tenantSchema);

                var model = builder.Build(connection);
                return model.Compile();
            });

        return new ContactContext(connection, compiledModel);
    }

    /// <summary>
    /// Creates the database and/or tables for a new tenant
    /// </summary>
    public static void ProvisionTenant(string tenantSchema, DbConnection connection)
    {
        using (var ctx = Create(tenantSchema, connection))
        {
            if (!ctx.Database.Exists())
            {
                ctx.Database.Create();
            }
            else
            {
                var createScript = ((IObjectContextAdapter)ctx).ObjectContext.CreateDatabaseScript();
                ctx.Database.ExecuteSqlCommand(createScript);
            }
        }
    }
}

The main idea of these codes is to provide a static method to create different DbContext by different schema and cache them with certain identifiers.

snys98
  • 96
  • 4
2

You can use Table attribute on the fixed schema tables.

You can't use attribute on schema changing tables and you need to configure that via ToTable fluent API.
If you disable the model cache (or you write your own cache), the schema can change on every request so on the context creation (every time) you can to specify the schema.

This is the base idea

class MyContext : DbContext
{
    public string Schema { get; private set; }

    public MyContext(string schema) : base()
    {

    }

    // Your DbSets here
    DbSet<Emp> Emps { get; set; }

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder.Entity<Emp>()
            .ToTable("Emps", Schema);
    }
}

Now, you can have some different ways to determine the schema name before creating the context.
For example you can have your "system tables" on a different context so on every request you retrieve the schema name from the user name using the system tables and than create the working context on the right schema (you can share tables between contexts).
You can have your system tables detached from the context and use ADO .Net to access to them.
Probably there are several other solutions.

You can also have a look here
Multi-Tenant With Code First EF6

and you can google ef multi tenant

EDIT
There is also the problem of the model caching (I forgot about that). You have to disable the model caching or change the behavior of the cache.

Community
  • 1
  • 1
bubi
  • 6,414
  • 3
  • 28
  • 45
  • Thank you for reply, but [as far as I know](http://stackoverflow.com/questions/39093542/entity-framework-6-disable-modelcaching) `OnModelCreating` method called just once and I have no way to change schema name via it on every request. Actually I use EF Core, but `OnModelCreating`'s behavior is the same. @bricelam has said about two ways to solve my issue, so I'm interested in some more detailed explanation, because EF's developer should know about EF something more then other man, hmm? – user3272018 Sep 19 '16 at 08:18
  • In SO question you posted there is `IDbModelCacheKeyProvider` that seems similar to `IModelCacheKeyFactory`. Maybe it's the key to solve my issue. I missed that article -- thank you. – user3272018 Sep 19 '16 at 08:28
  • You are right!!! I forgot about the model caching! Take also care about the performances (you can find some articles around, also on Stack Overflow) – bubi Sep 19 '16 at 09:11
2

maybe I'm a bit late to this answer

my problem was handling different schema with the same structure lets say multi-tenant.

When I tried to create different instances of the same context for the different schemas, Entity frameworks 6 comes to play, catching the first time the dbContext was created then for the following instances they were creates with a different schemas name but onModelCreating were never called meaning that each instance was pointing to the same previously catched Pre-Generated Views, pointing to the first schema.

Then I realized that creating new classes inheriting from myDBContext one for each schema will solve my problem by overcoming entity Framework catching problem creating one new fresh context for each schema, but then comes the problem that we will end with hardcoded schemas, causing another problem in terms of code scalability when we need to add another schema, having to add more classes and recompile and publish a new version of the application.

So I decided to go a little further creating, compiling and adding the classes to the current solution in runtime.

Here is the code

public static MyBaseContext CreateContext(string schema)
{
    MyBaseContext instance = null;
    try
    {
        string code = $@"
            namespace MyNamespace
            {{
                using System.Collections.Generic;
                using System.Data.Entity;

                public partial class {schema}Context : MyBaseContext
                {{
                    public {schema}Context(string SCHEMA) : base(SCHEMA)
                    {{
                    }}

                    protected override void OnModelCreating(DbModelBuilder modelBuilder)
                    {{
                        base.OnModelCreating(modelBuilder);
                    }}
                }}
            }}
        ";

        CompilerParameters dynamicParams = new CompilerParameters();

        Assembly currentAssembly = Assembly.GetExecutingAssembly();
        dynamicParams.ReferencedAssemblies.Add(currentAssembly.Location);   // Reference the current assembly from within dynamic one
                                                                            // Dependent Assemblies of the above will also be needed
        dynamicParams.ReferencedAssemblies.AddRange(
            (from holdAssembly in currentAssembly.GetReferencedAssemblies()
             select Assembly.ReflectionOnlyLoad(holdAssembly.FullName).Location).ToArray());

        // Everything below here is unchanged from the previous
        CodeDomProvider dynamicLoad = CodeDomProvider.CreateProvider("C#");
        CompilerResults dynamicResults = dynamicLoad.CompileAssemblyFromSource(dynamicParams, code);

        if (!dynamicResults.Errors.HasErrors)
        {
            Type myDynamicType = dynamicResults.CompiledAssembly.GetType($"MyNamespace.{schema}Context");
            Object[] args = { schema };
            instance = (MyBaseContext)Activator.CreateInstance(myDynamicType, args);
        }
        else
        {
            Console.WriteLine("Failed to load dynamic assembly" + dynamicResults.Errors[0].ErrorText);
        }
    }
    catch (Exception ex)
    {
        string message = ex.Message;
    }
    return instance;
}

I hope this help someone to save some time.

Randy
  • 21
  • 3
0

Update for MVC Core 2.1

You can create a model from a database with multiple schemas. The system is a bit schema-agnostic in its naming. Same named tables get a "1" appended. "dbo" is the assumed schema so you don't add anything by prefixing a table name with it the PM command

You will have to rename model file names and class names yourself.

In the PM console

Scaffold-DbContext "Data Source=localhost;Initial Catalog=YourDatabase;Integrated Security=True" Microsoft.EntityFrameworkCore.SqlServer -OutputDir Models -force -Tables TableA, Schema1.TableA
0

I actually found it to be a simpler solution with an EF interceptor.

I actually keep the onModeling method:

  protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder.HasDefaultSchema("dbo"); // this is important to always be dbo

        // ... model definition ...
    }

And this code will be in Startup:

    public void ConfigureServices(IServiceCollection services)
    {
        // if I add a service I can have the lambda (factory method) to read from request the schema (I put it in a cookie)
        services.AddScoped<ISchemeInterceptor, SchemeInterceptor>(provider =>
        {
            var context = provider.GetService<IHttpContextAccessor>().HttpContext;

            var scheme = "dbo";
            if (context.Request.Cookies["schema"] != null)
            {
                scheme = context.Request.Cookies["schema"];
            }

            return new SchemeInterceptor(scheme);
        });

        services.AddDbContext<MyContext>(options =>
        {
            var sp = services.BuildServiceProvider();
            var interceptor = sp.GetService<ISchemeInterceptor>();
            options.UseSqlServer(Configuration.GetConnectionString("Default"))
                .AddInterceptors(interceptor);
        });

And the interceptor code looks something like this (but basically we use ReplaceSchema):

public interface ISchemeInterceptor : IDbCommandInterceptor
{

}

public class SchemeInterceptor : DbCommandInterceptor, ISchemeInterceptor
{
    private readonly string _schema;

    public SchemeInterceptor(string schema)
    {
        _schema = schema;
    }

    public override Task<InterceptionResult<object>> ScalarExecutingAsync(DbCommand command, CommandEventData eventData, InterceptionResult<object> result,
        CancellationToken cancellationToken = new CancellationToken())
    {
        ReplaceSchema(command);
        return base.ScalarExecutingAsync(command, eventData, result, cancellationToken);
    }

    public override InterceptionResult<object> ScalarExecuting(DbCommand command, CommandEventData eventData, InterceptionResult<object> result)
    {
        ReplaceSchema(command);
        return base.ScalarExecuting(command, eventData, result);
    }

    public override Task<InterceptionResult<int>> NonQueryExecutingAsync(DbCommand command, CommandEventData eventData, InterceptionResult<int> result,
        CancellationToken cancellationToken = new CancellationToken())
    {
        ReplaceSchema(command);
        return base.NonQueryExecutingAsync(command, eventData, result, cancellationToken);
    }

    public override InterceptionResult<int> NonQueryExecuting(DbCommand command, CommandEventData eventData, InterceptionResult<int> result)
    {
        ReplaceSchema(command);
        return base.NonQueryExecuting(command, eventData, result);
    }

    public override InterceptionResult<DbDataReader> ReaderExecuting(
        DbCommand command,
        CommandEventData eventData,
        InterceptionResult<DbDataReader> result)
    {
        ReplaceSchema(command);
        return result;
    }

    public override Task<InterceptionResult<DbDataReader>> ReaderExecutingAsync(DbCommand command, CommandEventData eventData, InterceptionResult<DbDataReader> result,
        CancellationToken cancellationToken = new CancellationToken())
    {
        ReplaceSchema(command);
        return base.ReaderExecutingAsync(command, eventData, result, cancellationToken);
    }

    private void ReplaceSchema(DbCommand command)
    {
        command.CommandText = command.CommandText.Replace("[dbo]", $"[{_schema}]");
    }

    public override void CommandFailed(DbCommand command, CommandErrorEventData eventData)
    {
        // here you can handle cases like schema not found
        base.CommandFailed(command, eventData);
    }

    public override Task CommandFailedAsync(DbCommand command, CommandErrorEventData eventData,
        CancellationToken cancellationToken = new CancellationToken())
    {
        // here you can handle cases like schema not found
        return base.CommandFailedAsync(command, eventData, cancellationToken);
    }


}
Alin Ciocan
  • 3,082
  • 4
  • 34
  • 47
0

If the only difference between databases is schema name the simplest way to get rid of the problem is to remove line of code which is setting the default schema in OnModelCreating method:

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
    ...
    modelBuilder.HasDefaultSchema("YourSchemaName"); <-- remove or comment this line
    ...
}

In this case underneeth sql queries run by EF Core won't contain schema name in their FROM clause. Then you will be able to write a method which will set correct DbContext depending on your custom conditions. Here is an example which I used to connect to different Oracle databases with the same database structure (in short let's say that in Oracle schema is the same as user). If you're using another DB you just need to put correct connection string and then modify it.

private YourDbContext SetDbContext()
{
    string connStr = @"Data Source=(DESCRIPTION=(ADDRESS_LIST=(ADDRESS=(PROTOCOL=TCP)(HOST=server_ip)(PORT=1521)))(CONNECT_DATA=(SID = server_sid)));User Id=server_user ;Password=server_password";

    //You can get db connection details e.g. from app config
    List<string> connections = config.GetSection("DbConneections");
    string serverIp;
    string dbSid;
    string dBUser;
    string dbPassword;

    /* some logic to choose a connection from config and set up string variables for a connection*/

    connStr = connStr.Replace("server_ip", serverIp);
    connStr = connStr.Replace("server_sid", dbSid);
    connStr = connStr.Replace("server_user", dBUser);
    connStr = connStr.Replace("server_password", dbPassword);

    var dbContext = dbContextFactory.CreateDbContext();
    dbContext.Database.CloseConnection();
    dbContext.Database.SetConnectionString(connStr);

    return dbContext;
}

Finally you will be able to set desired dbContext where it's needed invoking this method before, you can also pass some arguments to the method to help you choose correct db.

maniacz
  • 9
  • 2
  • How does that set the *desired* schema name? – Gert Arnold Apr 18 '21 at 18:35
  • @GertArnold I eddited my answer, take a look. – maniacz Apr 20 '21 at 17:24
  • Still has nothing to do with setting the schema. Check the meaning of the word 'schema' in the context of this question. – Gert Arnold Apr 28 '21 at 10:21
  • Sometimes people tend to solve their issues by "adding" something that will help them, and seem to overlook solutions which are based on "subtraction". In this question I can imagine that one can have this kind of an issue described in the title and as I mentioned in my answer if THE ONLY difference is the schema name, so you basically have different DBs with the same entities, you can get rid of setting schema by EF Core and it solves the issue, anyway it solved mine so I decided to share this approach. – maniacz May 05 '21 at 07:20
  • You don't seem to realize that OP *needs* to set a schema, because of multi-tenancy. Queries without a schema prefix don't fit the bill and changing a connection string at runtime is not the issue. – Gert Arnold May 05 '21 at 07:35