我正在开发一个服务基础应用程序。在服务方面,我必须将Expression
转换为Func<TypeOfEntity,bool>
才能在EntityFramework查询中使用。
Type typeofEntity;// we just have type of entity and I could get it from entity name and assembly name
//ExpressionSerializer is in Serialize.Linq
ExpressionSerializer expressionSerializer = new ExpressionSerializer(new JsonSerializer());
Expression expr = expressionSerializer.DeserializeText(stringFromClient);//It's Ok until here
Func<?,bool> func = ?//How can I create Func of typeofEntity and bool
var result = Entities.Something.Where(func);
我们如何将Expression
(不是Expression<Func<T,bool>>
)转换为Func<T,bool>
?
答案 0 :(得分:3)
您可以使用dynamic
类型在运行时解析T
。像这样的课程
static class ExpressionRunner
{
public static IList<T> Run<T>(
Context context,
Expression<Func<T, bool>> expression)
where T : class
{
var result = context
.Set<T>()
.Where(expression);
return result.ToList();
}
}
可以针对Expression
Context
Expression expr = expressionSerializer.DeserializeText(stringFromClient);
var result = ExpressionRunner.Run(Entities, expr as dynamic);
请注意,返回类型也是dynamic
,因此建议在调用链的顶部使用此Run
方法以最大限度地提高性能 - 即Run
应返回{{ 1}}并且所有处理都应嵌套在void
内。