I need to create a Global Query Filter that filters only those Users who belong belong to a certain Tenant.
However, I get a stackoverflow when adding the queryfilter to OnModelCreating.
I get the TenantId from the current logged in user, using IHttpContextAccessor. This works quite fine with other Entities, but ApplicationUser creates the error. Is this perhaps a problem of circular code?
My ApplicationDbContext is as follows (abbreviated for clarity purposes)
public class ApplicationDbContext
: IdentityDbContext<ApplicationUser, ApplicationRole, string, IdentityUserClaim<string>,
ApplicationUserRole, IdentityUserLogin<string>,
IdentityRoleClaim<string>, IdentityUserToken<string>>
{
private readonly IHttpContextAccessor _contextAccessor;
public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options, IHttpContextAccessor contextAccessor)
: base(options)
{
_contextAccessor = contextAccessor;
}
public virtual Guid? CurrentTenantId
{
get
{
return Users.FirstOrDefault(u => u.UserName == _contextAccessor.HttpContext.User.Identity.Name)?.TenantId;
}
}
public virtual string CurrentUserName
{
get
{
return Users.FirstOrDefault(u => u.UserName == _contextAccessor.HttpContext.User.Identity.Name)?.UserName;
}
}
public DbSet<ApplicationUser> ApplicationUser { get; set; }
public DbSet<Tenant> Tenant { get; set; }
protected override void OnModelCreating(ModelBuilder builder)
{
base.OnModelCreating(builder);
builder.Entity<Tenant>().HasQueryFilter(e => e.TenantId == CurrentTenantId);
builder.Entity<ApplicationUser>().HasQueryFilter(e => e.TenantId == CurrentTenantId);
}
}
}
I have added services.AddHttpContextAccessor()
to the ConfifureServices section in my startup.
Any suggestions on how to resolve this?
Users
dataset, but to be able to read it you have to have a DbContext initialized first, so .net will try to initialize a DbContext class. And now you have got yourself stuck in aninfinite loop
. Because DbContext needs to read the Users Dbset and the Users dbset needs an DbContext so it will try to create one. The solution to this problem is taking the logic for retrieving the TenantId outside of your DbContext class.