How to use System.Linq.Expressions.Expression to filter based on children?

.net, c#, expression, linq-to-sql

Solution

If you want to combine expressions and still be able to use linq-to-sql, you may want to have a look at LinqKit. It walks inside your expression and replaces all the function calls by their contents before the sql conversion.

This way you'll be able to use directly

return db.Parents
       .AsExpandable()
       .Where(parent => parent.Status == 1 && filter(parent.Child));

Problem

I have a filter that I use across many methods: ``` Expression<Func<Child, bool>> filter = child => child.Status == 1; ``` (actually is more complex than that) And I have to do the following ``` return db.Parents.Where(parent => parent.Status == 1 && parent.Child.Status == 1); ``` where the condition is the same as in the filter above. I want to reuse the filter in this method. But I don't know how. I tried ``` return db.Parents.Where(parent => parent.Status == 1 && filter(parent.Child)); ``` but an Expression can't be used as a method

Original source

Related problems