在C#?</type,>中将表达式转换为Func <type,bool =“”>

时间:2013-12-13 10:41:45

标签: c# entity-framework expression

我正在开发一个服务基础应用程序。在服务方面,我必须将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>

1 个答案:

答案 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内。