问题
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
回答1:
As suggested in the comments its better to use Dynamic Linq. As find() is the equivalent of Where().FirstOrdefault():
List<T>.AsQueryable().Where("CategoryId = 5 and Price < 10").FirstOrDefault();
回答2:
I used System.Linq.Dynamic which is based on a previous work by MicroSoft
Install-Package System.Linq.Dynamic
I Implemented the following static /Extension methods:
using System;
using System.Collections.Generic;
using DynamicExpression=System.Linq.Dynamic.DynamicExpression; //nuget package
using System.Linq.Expressions;
public static class MyDynamics
{
public static Predicate<T> GetPredicate<T>(string stringExpression)
{
var exp = DynamicExpression.ParseLambda<T, bool>(stringExpression).Compile();
var predicate = new Predicate<T>(exp);
return predicate;
}
}
How To Use:
Console.WriteLine("------- Find items using string expression ------");
//use string expression
var predicate = MyDynamics.GetPredicate<Part>("PartId==1444");
//pass the predicate to List.Find
var part= parts.Find(predicate);
Console.WriteLine("Part: Find: PartId= {0} , PartName={1}",part.PartId, part.PartName);
Life Demo in Fiddle
来源:https://stackoverflow.com/questions/48868277/how-to-get-predicatet-from-string-expressions-at-runtime