This is my scenario: I need to extract data from an entity using an "OR" query on a a property in a linked entity.
These are my entities:
public class Dealer
{
public virtual int id{get;set;}
public virtual string name{get;set;}
public virtual IList<Car> Cars{get;set;}
}
public class Car
{
public virtual int id{get;set;}
public virtual string name{get;set;}
public virtual int kw{get;set;}
}
Example: I want to extract all dealers that have cars with 98kw or 100kw. Sql Example:
SELECT Dealers.* FROM Dealers INNER JOIN Cars ON Cars.IdDealer = Dealers.Id WHERE Cars.kw = 98 OR Cars.kw = 100
I tried to use Expression trees but i don't know how to use them. I tried this:
var dealers = Session.Linq<Dealers>();
ParameterExpression pe = Expression.Parameter(typeof(int), "kw");
Expression tot = null;
var powers = new int[2]{98, 100};
for (var i = 0; i < powers.Length; i++)
{
Expression right = Expression.Constant(int.Parse(powers[i]));
if (i > 0)
tot = Expression.Or(tot, Expression.Equal(pe, right));
else
tot = Expression.Equal(pe, right);
}
dealers = dealers.Where(x => x.Cars.Any(Expression.Lambda<Func<Cars, bool>>(tot, null)));
but i get these compiler errors on the last row where I try to execute the Expression:
- Cannot convert lambda expression to type
string
because it is not a delegate type System.Collections.Generic.IList<Cars>
does not contain a definition forAny
and the best extension method overload System.Linq.Enumerable.Any(System.Collections.Generic.IEnumerable, System.Func) has some invalid arguments- Argument 2: cannot convert from
System.Linq.Expressions.Expression<System.Func<Cars,bool>>
toSystem.Func<Cars,bool>
Any suggestions?