Using the following example i would like to use my Expression
inside my Contains method, having it pass the query onto sql server using the EF
.
How can i build this up to work correctly?
void Main()
{
IQueryable<Person> qry = GetQueryableItemsFromDB();
var filtered = qry.Filter(p=>p.CompanyId);
}
public static class Ext
{
public static IQueryable<T> Filter<T>(this IQueryable<T> items, Expression<Func<T, int>> resolveCompanyIdExpression)
{
IEnumerable<int> validComps = GetCompanyIdsFromDataBase();
var exp = Expression.Lambda<Func<T, bool>>(
Expression.Call(typeof(Queryable),"Contains", new[] { typeof(Company) },
Expression.Constant(validComps),
resolveCompanyIdExpression.Body),
resolveCompanyIdExpression.Parameters[0]);
return items.Where(exp);
}
public static IQueryable<T> Filter<T>(this IQueryable<T> items, Expression<Func<T, IEnumerable<int>>> resolveCompanyIdExpression)
{
IEnumerable<int> validComps = GetCompanyIdsFromDataBase();
//No Idea what to do here ?
}
}
public class Person
{
public int CompanyId {get;set;}
}
I know i could pass in the entire predicate but i only want the user to supply how to resolve the Company from the entity in question.
UPDATE
I have decided to resolve the companyId rather than the entire company entity, i can get the list of ids in memory and im not fussed if that is IQueryable or just a plain array/IEnumerable
However i get some strange errors :
An exception occured during the execution of ' Extent.Select(o => o).Where(p => (p.Hide = False)).Where(p => (p.Archived = False)).Where(item => System.Int32[].Contains(item.Development.CompanyId))'. See InnerException for more details.
Inner exception is
Argument expression is not valid
UPDATE 2
I have edited the code to reflect what i would really like like to do, not having much luck on finding a solution to this.
Isn't the
items
parameter anIQueryable
? If so, try this:try Expression.Compile() method:
If I'm understanding correctly, what you want is expression composition:
Below is the implementation of the Compose() extension method on expression: