title: MultiTenancy with DbContext and TenantId - Interceptors, Filters, EF Code-First
body: <p>My organization needs to have a shared database, shared schema multitenant database.  We will be querying based on TenantId.  We will have very few tenants (less than 10) and all will share the same database schema with no support for tenant-specific changes or functionality.  Tenant metadata will be stored in memory, not in the DB (static members).</p>
  
  <p>This means all entities will now need a TenantId, and <code>DbContext</code> needs to know to filter on this by default.</p>
  
  <p>The <code>TenantId</code> will likely be identified by a header value or the originating domain, unless there's a more advisable approach.</p>
  
  <p>I've seen various samples leveraging interceptors for this but haven't seen a clearcut example on a TenantId implementation. </p>
  
  <hr>
  
  <p>The problems we need to solve: </p>
  
  <ol>
  <li>How do we modify the current schema to support this (simple I think, just add TenantId)</li>
  <li>How do we detect the tenant (simple as well - base it on the originating request's domain or header value - pulling from a BaseController)</li>
  <li>How do we propagate this to service methods (a little trickier... we use DI to hydrate via constructors... want to avoid peppering all of the method signatures with <code>tenantId</code>)</li>
  <li>How do we modify DbContext to filter on this tenantId once we have it (no idea) </li>
  <li>How do we optimize for performance.  What indexes do we need, how can we ensure that query caching isn't doing anything funky with the tenantId isolation, etc (no idea)</li>
  <li>Authentication - using SimpleMembership, how can we isolate <code>User</code>s, somehow associating them with a tenant.</li>
  </ol>
  
  <p>I think the biggest question there is 4 - modifying DbContext.</p>
  
  <hr>
  
  <p>I like how this article leverages RLS, but I'm not sure how to handle this in a code-first, dbContext manner: </p>
  
  <p><a href="https://azure.microsoft.com/en-us/documentation/articles/web-sites-dotnet-entity-framework-row-level-security/" rel="noreferrer">https://azure.microsoft.com/en-us/documentation/articles/web-sites-dotnet-entity-framework-row-level-security/</a></p>
  
  <p><strong>I'd say what I'm looking for is a way to - with performance in mind - selectively query tenantId-isolated resources using DbContext without peppering my calls with <code>"AND TenantId = 1"</code> etc.</strong></p>
  
  <hr>
  
  <p>Update - I found some options, but I'm not sure what the pros and cons are for each, or whether or not there's some "better" approach altogether.  My evaluation of options comes down to:</p>
  
  <ul>
  <li>Ease of implementation</li>
  <li>Performance</li>
  </ul>
  
  <hr>
  
  <p><strong>APPROACH A</strong></p>
  
  <p>This seems "expensive" since every time we new up a dbContext, we have to re-initialize filters: </p>
  
  <p><a href="https://blogs.msdn.microsoft.com/mvpawardprogram/2016/02/09/row-level-security-in-entityframework-6-ef6/" rel="noreferrer">https://blogs.msdn.microsoft.com/mvpawardprogram/2016/02/09/row-level-security-in-entityframework-6-ef6/</a></p>
  
  <p>First, I set up my tenants and interface:</p>
  
  <pre><code>public static class Tenant {
  
      public static int TenantA {
          get { return 1; }
      }
      public static int TenantB
      {
          get { return 2; }
      }
  
  }
  
  public interface ITenantEntity {
      int TenantId { get; set; }
  }
  </code></pre>
  
  <p>I implement that interface on any entities: </p>
  
  <pre><code> public class Photo : ITenantEntity
   {
  
      public Photo()
      {
          DateProcessed = (DateTime) SqlDateTime.MinValue;
      }
  
      [Key]
      public int PhotoId { get; set; }
  
      [Required]
      public int TenantId { get; set; }
   }
  </code></pre>
  
  <p>And then I update my DbContext implementation: </p>
  
  <pre><code>  public AppContext(): base("name=ProductionConnection")
      {
          Init();
      }
  
    protected internal virtual void Init()
      {
          this.InitializeDynamicFilters();
      }
  
      int? _currentTenantId = null;
  
      public void SetTenantId(int? tenantId)
      {
          _currentTenantId = tenantId;
          this.SetFilterScopedParameterValue("TenantEntity", "tenantId", _currentTenantId);
          this.SetFilterGlobalParameterValue("TenantEntity", "tenantId", _currentTenantId);
          var test = this.GetFilterParameterValue("TenantEntity", "tenantId");
      }
  
      public override int SaveChanges()
      {
          var createdEntries = GetCreatedEntries().ToList();
          if (createdEntries.Any())
          {
              foreach (var createdEntry in createdEntries)
              {
                  var isTenantEntity = createdEntry.Entity as ITenantEntity;
                  if (isTenantEntity != null &amp;&amp; _currentTenantId != null)
                  {
                      isTenantEntity.TenantId = _currentTenantId.Value;
                  }
                  else
                  {
                      throw new InvalidOperationException("Tenant Id Not Specified");
                  }
              }
  
          }
      }
  
      private IEnumerable&lt;DbEntityEntry&gt; GetCreatedEntries()
      {
          var createdEntries = ChangeTracker.Entries().Where(V =&gt; EntityState.Added.HasFlag(V.State));
          return createdEntries;
      }
  
     protected override void OnModelCreating(DbModelBuilder modelBuilder)
      {
          modelBuilder.Filter("TenantEntity", (ITenantEntity tenantEntity, int? tenantId) =&gt; tenantEntity.TenantId == tenantId.Value, () =&gt; null);
  
          base.OnModelCreating(modelBuilder);
      }
  </code></pre>
  
  <p>Finally, in my calls to DbContext, I use this: </p>
  
  <pre><code>     using (var db = new AppContext())
       {
            db.SetTenantId(someValueDeterminedElsewhere);
       }
  </code></pre>
  
  <p>I have a problem with this because I new up my AppContext in about a million places (some service methods need it, some don't) - so this bloats my code a bit.  There are also questions about tenant determination - do I pass in the HttpContext, do I force my controllers to pass the TenantId into all service method calls, how do I handle cases where I don't have an originating domain (webjob calls etc).</p>
  
  <hr>
  
  <p><strong>APPROACH B</strong></p>
  
  <p>Found here: <a href="http://howtoprogram.eu/question/n-a,28158" rel="noreferrer">http://howtoprogram.eu/question/n-a,28158</a></p>
  
  <p>Seems similar, but simple:</p>
  
  <pre><code> public interface IMultiTenantEntity {
        int TenantID { get; set; }
   }
  
   public partial class YourEntity : IMultiTenantEntity {}
  
   public partial class YourContext : DbContext
   {
   private int _tenantId;
   public override int SaveChanges() {
      var addedEntities = this.ChangeTracker.Entries().Where(c =&gt; c.State == EntityState.Added)
          .Select(c =&gt; c.Entity).OfType&lt;IMultiTenantEntity&gt;();
  
      foreach (var entity in addedEntities) {
          entity.TenantID = _tenantId;
      }
      return base.SaveChanges();
  }
  
  public IQueryable&lt;Code&gt; TenantCodes =&gt; this.Codes.Where(c =&gt; c.TenantID == _tenantId);
  }
  
  public IQueryable&lt;YourEntity&gt; TenantYourEntities =&gt; this.YourEntities.Where(c =&gt; c.TenantID == _tenantId);
  </code></pre>
  
  <p>Although this just seems like a dumb version of A with the same concerns.  </p>
  
  <p>I figure by this point in time, there has to be a mature, advisable configuration/architecture to suit this need.  How should we go about this?</p>