Search code examples
c#entity-frameworkasp.net-coreentity-framework-coremulti-tenant

Entity Framework MultiTenant Per User


I've applied multi tenant by entity framework core (shared schema , shared database ) and the tenant Id stored in http Context request , it will be resolved after the user login but most of time tenant Id not changed with different logged in users

My Table :

public class Blog
{ 
    private int _tenantId;  

    public int BlogId { get; set; }
    public string Name { get; set; }
    public string Url { get; set; } 
    public List<Post> Posts { get; set; }
}

My Db Context

PUBLIC dbContext:DbContext
{
   PRIVATE int tenantId;
   public dbContext(DbContextOptions<dbContext> options): base(options) { 
        //securityHelper IS EXTERNAL LIBRARY
        this.tenantId = securityHelper.GetClaim<INT>("tenantId");
   }
   protected override void OnModelCreating(ModelBuilder modelBuilder)
   {
      modelBuilder.Entity<AccountsTransactions>().HasQueryFilter(p=>p._tenantId == this.tenantId);
   }

}


Solution

  • You have an error. You defined _tenantId in a Blog class but trying to use it in AccountsTransactions class. Should be like this :

     modelBuilder.Entity<Blog>().HasQueryFilter(p=>p._tenantId == this.tenantId);
    

    but I am amazed how you could reach private _tenandId in " p._tenantId"?

    If you define property as private you should use this syntax:

    modelBuilder.Entity<Blog>().HasQueryFilter(p => EF.Property<int>(p, "_tenantId") == this.tenantId);