.net core MVC 9.x
I have the following code with my ZeroDbContext:
`
protected virtual long[] GetCurrentUserOrganizationUnitIds()
{
var userOuClaim = PrincipalAccessor.Principal?.Claims.FirstOrDefault(c => c.Type == ClaimsConstants.OrganizationUnitClaimKey);
if (string.IsNullOrEmpty(userOuClaim?.Value))
{
return Array.Empty<long>();
}
return userOuClaim.Value.Split(',', StringSplitOptions.RemoveEmptyEntries)
.Select(long.Parse)
.ToArray();
}
protected override Expression<Func<TEntity, bool>> CreateFilterExpression<TEntity>()
{
var expression = base.CreateFilterExpression<TEntity>();
if (typeof(OrganizationUnit).IsAssignableFrom(typeof(TEntity)))
{
if (IsOrganizationUnitFilterEnabled)
{
Expression<Func<TEntity, bool>> organizationUnitFilter = e => CurrentOUId.Contains(((IEntity<long>) e).Id);
expression = expression == null ? organizationUnitFilter : CombineExpressions(expression, organizationUnitFilter);
}
}
return expression;
}
`
The problem I have is that PrincipalAccessor.Principal?.Claims.FirstOrDefault(c => c.Type == ClaimsConstants.OrganizationUnitClaimKey);
always returns null.
My working assumption is that filters are created only once when the context is first instantiated and there is no Principal at that time.
I believe other values used within the ZeroDbContext such as CurrentTenantId are provided to the context from the AbpSession.
Question How can I add an EF filter that is based on data that is within the PrincipalAccessor.Principal at the time the query is executed?
2 Answer(s)
-
0
Hi,
Do you use it as explained in https://aspnetboilerplate.com/Pages/Documents/Articles\How-To\add-custom-data-filter-ef-core#configure-dbcontext ?
You can also take a look at https://github.com/aspnetboilerplate/aspnetboilerplate/blob/dev/src/Abp.EntityFrameworkCore/EntityFrameworkCore/AbpDbContext.cs#L78
By default, you are right, it should be executed once but if you use it as we do in AbpDbContext, the method will be executed each time when it is needed.
-
0
Thanks for the response; I have since relealised that I had not iimplemented this correctly.