Im currently working on an asp.net web api 2 application. Please bare in mind my experience is in php,js,css and so on and not c#.
Im hoping someone can help me with my generic IQueryable Extension that uses the Linq Expressions tree.
I have 3 tables (Entity Framework).
Trades
Id,Name
ProductTrades (linking table)
Id,Trade_Id,Product_Id
Products
Id,Code
i need to return all trades that has at least one product code from a list of product codes passed as a variable
I have this working fine with the following
list<string> tocheck = new list<string>("productcode1","productcode2");
var trades = db.Trades.SqlQuery(
"Select * from Trades T " +
"left join ProductTrades PT on T.Id = PT.Trade_Id " +
"left join Products P on PT.Product_Id = P.Id " +
"where P.Code in (@prod)", new SqlParameter("@prod", String.Join(",", tocheck))).ToList();
However i would like to use Linq Expression tree to achieve this to make it generic
See below for my attempt ( i have put this together using multiple sources while trying to learn it)
public static IQueryable<T> FilterWhereItemIn<T>(this IQueryable<T> queryable, string propertyOrFieldName, List<string> values)
{
var elementType = typeof(T);
var parameterExpression = Expression.Parameter(elementType);
var propertyOrFieldExpression = propertyOrFieldName.Split('.').Aggregate((Expression)parameterExpression, Expression.PropertyOrField);
var method = typeof(List<string>).GetMethod("Contains", new Type[] { typeof(string) });
var someValue = Expression.Constant(values, typeof(List<string>));
var containsExpression = Expression.Call(propertyOrFieldExpression, method, someValue);
var selector = Expression.Lambda<Func<T, bool>>(containsExpression, parameterExpression);
return queryable.Where(selector);
}
and i call this with the following (IQueryable queryable is the type Trade)
list<string> tocheck = new list<string>("productcode1","productcode2");
queryable.FilterWhereItemIn("Products.Code", tocheck );
However the i get the error message that "Code" does not exist. i assume this is because Products is a collection. does anyone know how to achieve this.
(ps sorry this post was a little rushed)