In Winform application using EntityFramework, I implement a generic Search / Filter UI Components using BindingSource of the BaseForm and build search/filter string expression dynamically from user inputs and properties of the DataSource of BindingSource (Context entity).
Find and Filter aren't supported by the BindingSource in EntityFramework, because the query result of ObjectContext or DataContext was IEnumerable type, which didn't implement IBindingList interface ref
As a workaround I Cast BindingSource
to List<T>
.
To implement one, I use List<T>.Find(predicate)
and the predicate is a lambda Expression.
To Pass a Predicate to List<T>.Find(predicate)
, I need To convert the dynamic generated string expression to Predicate .
String Expression example:
"CategoryId = 5 and Price < 10"
To Something using a method like:
Predicate<T> GetPredicate <T>(string expression)
{
//how to convert the string expressions to Predicate<T>
}
Then pass the predicate to the method List<T>. Find(predicat)
I can use .Where (dynamicStringExpression)
, but for my component I need GetPredicate(dynamicStringExpression)
How to get Predicate<T>
from string expressions
As suggested in the comments its better to use Dynamic Linq. As find() is the equivalent of Where().FirstOrdefault():
I used System.Linq.Dynamic which is based on a previous work by MicroSoft
I Implemented the following static /Extension methods:
How To Use:
Life Demo in Fiddle