I am using entity framework, and I need to create a dynamic expressions like:
var sel = Expression.Lambda<Func<TEntity, bool>>(propertyAccess, parameter);
var compiledSel = sel.Compile();
// sel = x.Name
// filter.Value = "John"
Repository.GetData.Where(item => compiledSel(item) != null && compiledSel(item).ToLower().StartsWith(filter.Value.ToString().ToLower()))
The above works with IQueriable, but I need it to work with entity framework.
That means I need to parse
item => compiledSel(item) != null && compiledSel(item).ToLower().StartsWith(filter.Value.ToString().ToLower())
to e.g.
x => x.Name != null && x.Name.StartsWith("John")
The reason I am doing this is because I have multiple entities I want to be able to filter dynamically.
Any suggestions?
Edit:
The query itself against EF is run here:
private IList<TEntity> GetCollection(Expression<Func<TEntity, bool>> where, Expression<Func<TEntity, object>>[] includes)
{
return DbSet
.Where(where)
.ApplyIncludes(includes)
.ToList();
}
When I run the query now the data where clause is Param_0 => (((Invoke(value(.... and I get The LINQ expression node type 'Invoke' is not supported in LINQ to Entities. error
class MyEntity:INameablewith propertystring Nameand then you can work withFunc<INameable, bool>dynamicallypropertyAccessvariable contain? String property accessor? Soselis actuallyExpression<Func<TEntity, string>>rather thanExpression<Func<TEntity, bool>>as in the example?IEnumerable<T>.Where(Func<T, bool>)overload which accepts anFunc<T, bool>instead ofIQueryable<T>.Where(Expression<Func<T, bool>>)which accepts an expression. Your problem is not that 'it works with IQueryable, but not with EF`.