I have a class which returns a predicate:
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
}
Now, the Predicate
property checks all of the fields. I want to check:
- Id
if it's not equal to Guid.Empty
;
- UserType
if it's not equal to None
;
- Roles
in the same way, iterate via collection, select only not None
elements and check it;
In the traditional way I can do this like that:
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();
}
}
How to do this in my scenario? I found the PredicateBuilder
class, can you show me how to solve my problem with this class?