如何调用没有参数的方法 which returns Expression<Func<Model, String>>?

How to call a method with no parameters which returns Expression<Func<Model, String>>?

我有这样的方法(非常简化的版本):

public static Expression<Func<MyModel, String>> GetSomeStatus()
{
    return myModel => myModel.IsTrue ? "That's true" : "That's false";
}

那么,我如何在这样的语句中调用它:

var efRequest = db.Table1.Where(...)
                            .Select(x => new MyAnotherModel
                            {
                                Status = ""; // call GetSomeStatus() here; x is of MyModel type
                            })

注意:我最初的问题是在 Select 方法中调用一些 returns String 的辅助方法,但当然我有像 Linq to entities doesn't recognize this method... 这样的异常,所以我尝试重写它(参见上面的示例),但现在我只是不明白如何调用它(我在 EF 中相对较新)。我知道 Select 之前的简单 AsEnumerable 调用解决了我最初的问题,但我想将此查询保留为 IQueryable 以备后用。

开箱即用是不可能的。但是您可以使用例如 LINQKit AsExpandableInvoke 扩展方法,如下所示:

首先你需要将表达式存储在一个变量中,否则你会得到著名的 Linq to entities doesn't recognize this method... 异常:

var getSomeStatus = GetSomeStatus();

然后在查询中使用它(在调用 AsExpandable 之后,因此生成的查询表达式树被正确地后处理):

var efRequest = db.Table1.AsExpandable()
    .Where(...)
    .Select(x => new MyAnotherModel
    {
        Status = getSomeStatus.Invoke(x)
    });