Db通用资源授权

问题描述 投票:0回答:1

我试图弄清楚如何根据角色动态授权我的上下文。

public interface IConstraintResolver
{
    Expression<Func<TEntity, bool>>[] GetConstraintsForTypeByRole<TEntity>() 
        where TEntity : class;
}
public class AuthorizationContext : DbContext
{
    protected IConstraintResolver _constraintResolver;
    public AuthorizationContext(IConstraintResolver constraintResolver)
    {
        this._constraintResolver = constraintResolver;
    }

    public override DbSet<TEntity> Set<TEntity>()
    {
        var defaultSet = base.Set<TEntity>();

        var constraints = this._constraintResolver.GetConstraintsForTypeByRole<TEntity>();

        var filteredSet = base.Set<TEntity>().AsQueryable();

        foreach(var constraint in constraints)
        {
            filteredSet = filteredSet.Where(constraint);
        }

        //how do I apply this back to the innerQueryable
        return filteredSet;
    }
}

我的问题是,在应用了我的可查询后,如何使其成为Set的默认可查询对象。

我发现了一个与老DbSet here一起使用的陀螺

但.Net Core不包含IDBSet

如何创建自定义dbset,或者如何过滤现有dbSet?

c# entity-framework authorization .net-core filtering
1个回答
1
投票

通过global filters有更好的方法:

public class AuthorizationContext : DbContext
{
    static AuthorizationContext()
    {
         QueryFilterManager.Filter<Orders>(q => q.Where(x => x.Price <= 5000));
    }

    public AuthorizationContext()
    {
         QueryFilterManager.InitilizeGlobalFilter(this);
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.