title: Dynamically changing schema in Entity Framework Core
body: <p><strong>UPD</strong> <a href="https://stackoverflow.com/a/50529432/3272018">here</a> is the way I solved the problem. Although it's likely to be not the best one, it worked for me.</p>
  
  <hr>
  
  <p>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 <a href="https://stackoverflow.com/questions/37180426/how-to-change-database-schema-on-runtime-in-ef7-or-ef-core">similar question</a> about this issue but it's still unanswered and I have some different conditions. So I have the <code>Resolve</code> method that grants the db-context when necessary</p>
  
  <pre><code>public static void Resolve(IServiceCollection services) {
      services.AddIdentity&lt;ApplicationUser, IdentityRole&gt;()
          .AddEntityFrameworkStores&lt;DomainDbContext&gt;()
          .AddDefaultTokenProviders();
      services.AddTransient&lt;IOrderProvider, OrderProvider&gt;();
      ...
  }
  </code></pre>
  
  <p>I can set the schema-name in <code>OnModelCreating</code>, but, as was found before, this method is called just once, so I can set schema name globaly like that</p>
  
  <pre><code>protected override void OnModelCreating(ModelBuilder modelBuilder) {
      modelBuilder.HasDefaultSchema("public");
      base.OnModelCreating(modelBuilder);
  }
  </code></pre>
  
  <p>or right in the model via an attribute</p>
  
  <pre><code>[Table("order", Schema = "public")]
  public class Order{...}
  </code></pre>
  
  <p>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:</p>
  
  <ol>
  <li>Figure out the schema name by the user credentials;</li>
  <li>Get user-specific data from database from specific schema.</li>
  </ol>
  
  <p>Thank you.</p>
  
  <p>P.S. I use PostgreSql and this is the reason for lowecased table names.</p>