title: EF Core - multi tenant application with 2 DB Context
body: <p>Background:</p>
  <p>.NET 6 application (front-end Angular SPA)  Will be deployed as single application with 1 database per tenant. There is a shared  database (called GlobalContext) which holds Tenant and TenantUser information.</p>
  <p>In my Program.cs I don't have a connection string to the tenant database, as that information information is only available after a user has logged in.</p>
  <pre><code>builder.Services.AddDbContext&lt;GlobalContext&gt;(
  options =&gt; options.UseSqlServer(config.GetValue&lt;string&gt;(&quot;ConnectionStringGlobal&quot;))
  </code></pre>
  <p>);</p>
  <p>No connection string specified here</p>
  <pre><code>builder.Services.AddDbContext&lt;FinanceAppContext&gt;();
  </code></pre>
  <p>In the OnConfiguring method in the FinanceappContext I obtain the connection string using a service;</p>
  <pre><code>            var tenant = await _tenantService.GetConnectionString();
          optionsBuilder.UseSqlServer(_config.GetValue&lt;string&gt;(tenant));
  
          base.OnConfiguring(optionsBuilder);
  </code></pre>
  <p>The TenantService is a transient service which obtains the logged in users tenant from the GlobalContext</p>
  <pre><code>    public async Task&lt;string&gt; GetConnectionString() {
      try
      {
          var userId = _contextAccessor.HttpContext.User.FindFirst(ClaimTypes.Email).Value;
  
          var user = await _globalContext.TenantUser
              .Include(tenantuser =&gt; tenantuser.Tenant)
              .FirstOrDefaultAsync(tenantuser =&gt; tenantuser.EmailAddress == userId);
  
          return user.Tenant.Name;            
      }
      catch (System.Exception)
      {            
          return &quot;&quot;;
      }
  }
  </code></pre>
  <p>But when I try to access any data via the FinanceAppContext I get the following error;</p>
  <p><em><strong>A relational store has been configured without specifying either the DbConnection or connection string to use</strong></em></p>
  <p>It seems like the fact I don't specify a connection string in Program.cs and but do specify one in OnConfiguring seems to be an issue?</p>