我有一个返回谓词的类:
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
门课,你能告诉我如何解决这门课的问题吗?