Forgive my clumsy explanation, but I have a class that contains a List:
public class Document
{
public int OwnerId { get; set; }
public List<User> Users { get; set; }
public Document() { }
}
public class User
{
public string UserName { get; set; }
public string Department { get; set; }
}
Currently I use PredicateBuilder to perform dynamic queries on my objects. How can I turn the following LINQ statement into an Expression Tree:
var predicate= PredicateBuilder.True<User>();
predicate= predicate.And<User>(user => user.Deparment == "HR");
var deptDocs = documents.AsQueryable()
.Where(doc => doc.Users
.AsQueryable().Count(predicate) > 0)
.ToList();
In other words var deptDocs = documents.HasUserAttributes("Department", "HR").ToList();
. From what I can tell, my issue is not being able to evaluate the user => user.Deparment == "HR"
row by row if I were to issue an Expression.Invoke.
UPDATE:
I think I have made some progress on this:
var predicate = PredicateBuilder.True<User>();
predicate = predicate.And<User>(user => user.Department == "FIN");
Expression<Func<Document, bool>> userSelector =
doc => doc.Users
.AsQueryable()
.Any(predicate);
var docParm = Expression.Parameter(typeof(Document), "appDoc");
var body = Expression.Invoke(userSelector, docParm);
var lambda = Expression.Lambda<Func<Document, bool>>(body, docParm);
var allPredicate = PredicateBuilder.True<Document>();
allPredicate = allPredicate.And<Document>(doc => doc.OwnerId == 1);
allPredicate = allPredicate.And<Document>(lambda);
var hrDocs = this.docs.AsQueryable().Where(allPredicate).ToList();
Is there a more effective way to do this? How can I make an expression that creates the predicate - user => user.Department - with generics?