使用EF Core的自定义过滤器

时间:2019-01-23 20:49:59

标签: aspnetboilerplate

我在这里没有找到有关此主题的答案,但它们并未完全解决我的问题。 我的目标是使实体具有用户作为所有者。 我定义一个接口IMustHaveUser

public interface IMustHaveUser
{
    long UserId { get; set; }
}

然后我在我的实体产品中实现它

我通过预初始化方法在EFCoreModule中注册自定义过滤器

public override void PreInitialize() {
 //Register custom data filters
 Configuration.UnitOfWork.RegisterFilter("MustHaveUser", true);
 //other code here...
}

最后在DBContext中设置我的过滤器 定义一个属性,以检查是否启用了过滤器

protected virtual bool IsMustHaveUserFilterEnabled => CurrentUnitOfWorkProvider?.Current?.IsFilterEnabled("MustHaveUser") == true;

并重写CreateFilterExpression方法。

 protected override Expression<Func<TEntity, bool>> CreateFilterExpression<TEntity>()
    {
        var expression = base.CreateFilterExpression<TEntity>();

        if (typeof(IMustHaveUser).IsAssignableFrom(typeof(TEntity)))
        {
            Expression<Func<TEntity, bool>> userFilter = e => ((IMustHaveUser) e).UserId == AbpSession.UserId || (((IMustHaveUser) e).UserId == AbpSession.UserId) == IsMustHaveUserFilterEnabled;
            expression = expression == null ? userFilter : CombineExpressions(expression, userFilter);
        }


        return expression;
    }

现在,当我创建实体时,我必须手动设置UserID。 基本上我是使用方法在域层中编写ProductManager的

void Create(Product product, UserIdentity user){
    product.UserId = user.UserId;
    //Other business rules and insert with repository

}

我的问题是要设置当前的UserId。还有其他最简单(更好)的方法吗?

2 个答案:

答案 0 :(得分:1)

我忘记了DI。找到了解决方案。基本上,我已经将IAbpSession注入Automapper配置文件并在那里映射UserId。

public class AutoMapperProfile : AutoMapper.Profile
    {
        private IAbpSession _abpSession;

        public AutoMapperProfile()        {

            _abpSession = IocManager.Instance.Resolve<IAbpSession>();



            CreateMap<LicenseInput, License>()
                .ForMember(x => x.UserId, options => options.MapFrom(src => _abpSession.UserId));


        }
    }

答案 1 :(得分:0)

最终我做了另一种方法,因为这种方法使该代码难以进行集成测试。 我不知道为什么这时文档会丢失,我不得不从github阅读源代码以了解现有过滤器的工作方式,例如MustHaveTenant等。 我在AbpDbContext中找到了一个名为ApplyAbpConceptsForAddedEntity的多态方法,该方法可以实现该方法。

MyDbContext中的最终代码如下:

{{1}}