Moh*_*zam 6 c# entity-framework filter entity-framework-core ef-core-2.2
我正在使用 EF Core HasQueryFilter 扩展方法,该方法位于 OnModelCreating 方法内。
我使用服务将用户 ID 注入到 DbContext 中,然后将 userId 应用到查询过滤器。第一次执行 OnModelCreating 时,它按预期工作正常。但是,当我更改用户并将不同的 userId 传递给 DbContext 时,查询过滤器不会受到明显的影响,因为这次没有调用 OnModelCreating。
该应用程序的一些背景知识:它是一个核心 2.2 API 项目,使用 JWT 令牌对用户进行身份验证。我填充用户声明并使用 JWT 初始化注入的身份验证服务,因此对于每次调用 API,userId 可能不同,因此查询过滤器应该适用于不同的 userId。
示例代码如下:
public class SqlContext : DbContext
{
private readonly IAuthService _authService;
public SqlContext(DbContextOptions options, IAuthService authService) : base(options)
{
_authService = authService;
}
public DbSet<Device> Devices { get; set; }
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
modelBuilder.Entity<Device>().HasQueryFilter(p => !p.IsDeleted && p.ManufacturerId == _authService.ManufacturerId);
}
}
Run Code Online (Sandbox Code Playgroud)
DbContext 如何初始化。
services.AddDbContextPool<TContext>(o =>
o.UseSqlServer(configuration["Settings:SqlServer:DefaultConnection"],
b =>
{
b.MigrationsAssembly(configuration["Settings:SqlServer:MigrationAssembly"]);
b.CommandTimeout(60);
b.EnableRetryOnFailure(2);
})
.ConfigureWarnings(warnings =>
{
warnings.Throw(RelationalEventId.QueryClientEvaluationWarning);
}))
.AddTransient<TContext>();
Run Code Online (Sandbox Code Playgroud)
终于解决了。
由于过滤器正在工作,但在第一次请求后创建模型后,它就没有得到更新。原因是 EF 正在缓存创建的模型。因此,我必须实现IModelCacheKeyFactory才能根据过滤器捕获不同的模型。
internal class DynamicModelCacheKeyFactory : IModelCacheKeyFactory
{
public object Create(DbContext context)
{
if (context is SqlContext dynamicContext)
{
return (context.GetType(), dynamicContext._roleCategory);
}
return context.GetType();
}
}
Run Code Online (Sandbox Code Playgroud)
并将其附加到上下文中,如下所示。
protected override void OnConfiguring(DbContextOptionsBuilder builder)
{
base.OnConfiguring(builder);
builder.ReplaceService<IModelCacheKeyFactory, DynamicModelCacheKeyFactory>();
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
2273 次 |
最近记录: |