1

我有一个返回谓词的类:

public class UserPredicateBuilder 
    {
        public Guid Id{ get; set; }
        public IEnumerable<Role> Roles{ get; set; }
        public UserType UserType{ get; set; }


        protected override Expression<Func<User, bool>> Predicate
        {
            get
            {
                return l => l.UserType == UserType
                            && l.Id== Id
                            && Roles.Contains(l.Role);
            }
        }
    }

public enum UserType
{
   None,
   Admin,
   User,
   Guest
}

public enum Role
{
   None,
   Create,
   Delete,
   Update
}

现在,该Predicate属性检查所有字段。我想检查:
-Id如果它不等于Guid.Empty;
-UserType如果不等于None;
- Roles以同样的方式,通过集合进行迭代,只选择不None元素并检查它;

传统方式,我可以这样做:

public class SomeClass
{
   public Guid Id { get; set; }
   public IEnumerable<Role> Roles{ get; set; }
   public UserType UserType{ get; set; }

   public IList<User> GetUsers(some args)
   {
      IQueryable<User> query = ...;
      if(user.Id != Guid.Empty)
         query = query.Where(u=>u.Id == Id);

      if(user.UserType != UserType.None)
         query = query.Where(u=>u.UserType == UserType)

      ...

      return query.ToList();
    }
}

如何在我的场景中做到这一点?我找到了这PredicateBuilder门课,你能告诉我如何解决这门课的问题吗?

4

1 回答 1

1

您可以这样做(我不确定我是否正确阅读了您的要求,但希望这是一个有效的起点):

return l => (UserType == UserType.None || l.UserType == UserType)
          && (Id == Guid.Empty || l.Id == Id)
          && (!Roles.Any() || Roles.Where(r => r != Role.None).Contains(l.Role));
于 2013-10-25T10:09:14.690 回答