简体   繁体   English

将表达式转换为Func <Type, bool> 在c#?

[英]Converting Expression to Func<Type, bool> in c#?

I'm working on a service base application. 我正在研究服务基础应用程序。 At the service side, I have to convert Expression to Func<TypeOfEntity,bool> for using in an EntityFramework query. 在服务端,我必须将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);

How can we convert Expression (not Expression<Func<T,bool>> ) to Func<T,bool> ? 我们如何将Expression (不是Expression<Func<T,bool>> )转换为Func<T,bool>

You can use the dynamic type to have T resolved at runtime. 您可以使用dynamic类型在运行时解析T A class such as this 像这样的一个类

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();
    }

}

Can run the Expression against the Context 可以针对Context运行Expression

Expression expr = expressionSerializer.DeserializeText(stringFromClient);
var result = ExpressionRunner.Run(Entities, expr as dynamic);

Note that the return type is also dynamic so it would be advisable to have this Run method at the top of the call chain to maximise performance - ie Run should return void and all the processing should be nested inside of Run . 请注意,返回类型也是dynamic因此建议在调用链的顶部使用此Run方法以最大化性能 - 即Run应返回void并且所有处理应嵌套在Run

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM