[英]How can I make a dynamic query filter in entity framework core?
I'm using do.net
6, and I want to make a global query filter in ef core to check my authentication ID dynamically, but the OnModelCreating
runs just once in the lifecycle of ASP.net
.我正在使用
do.net
6,我想在 ef core 中创建一个全局查询过滤器来动态检查我的身份验证 ID,但是OnModelCreating
在ASP.net
的生命周期中只运行一次。 Do you have any ideas how to do this?你有什么想法如何做到这一点?
This is my OnModelCreating method.这是我的OnModelCreating方法。 DeletedAt type is DateTime?
DeletedAt类型是DateTime? and my authentication ID is CompanyId .
我的身份验证 ID 是CompanyId 。 I get _companyId from the constructor and the type of it is long?
我从构造函数中得到_companyId并且它的类型很长? .
. When a request is triggered, this ID fills, but my idea's problem is this method called at the startup of the project, At that time, the _companyId is null and never called again!
当触发请求时,这个ID就填上了,但我的想法的问题是这个方法在项目启动时调用,当时_companyId是null,之后就再也没有调用过!
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
modelBuilder.ApplyQueryFilters<IDeletedAt>(x => x.DeletedAt == null);
modelBuilder.ApplyQueryFilters<IDeletedAtAndCompany>(x => x.DeletedAt == null && x.CompanyId == _companyId);
}
This is my ApplyQueryFilters method if you need:如果您需要,这是我的ApplyQueryFilters方法:
public static void ApplyQueryFilters<T>(this ModelBuilder modelBuilder, Expression<Func<T, bool>> expression)
{
foreach (var entityType in modelBuilder.Model.GetEntityTypes())
{
if (entityType.ClrType.GetInterface(typeof(T).Name) == null) continue;
var newParam = Expression.Parameter(entityType.ClrType);
var newBody = ReplacingExpressionVisitor
.Replace(expression.Parameters.Single(), newParam, expression.Body);
modelBuilder.Entity(entityType.ClrType).HasQueryFilter(Expression.Lambda(newBody, newParam));
}
}
I think I need a new idea to resolve this issue.我想我需要一个新的想法来解决这个问题。
Add the companyId to your Db Context then initialize it when you create the DbContext or when authenticate (you should have a DbContext peer session):将 companyId 添加到您的 Db 上下文,然后在创建 DbContext 或进行身份验证时对其进行初始化(您应该有一个 DbContext 对等会话):
public class ApplicationDbContext
{
...
public long? _companyId ;
}
in your OnModelCreating add this default filter (adapt it to your case):在您的 OnModelCreating 添加此默认过滤器(根据您的情况进行调整):
modelBuilder.Entity<YourEntity>().HasQueryFilter(b => EF.Property<string>(b, "companyId") == _companyId );
change the _companyId when needed.需要时更改 _companyId。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.