Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/sql/75.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# “LINQ to Entities”无法投影单行字段,因为表达式没有Invoke()方法_C#_Sql_.net_Linq_Entity Framework - Fatal编程技术网

C# “LINQ to Entities”无法投影单行字段,因为表达式没有Invoke()方法

C# “LINQ to Entities”无法投影单行字段,因为表达式没有Invoke()方法,c#,sql,.net,linq,entity-framework,C#,Sql,.net,Linq,Entity Framework,在这个问题的基础上,我正在尝试实现一种扩展方法,以在LINQ中为SQL提供TIES功能,我可以按照下面的建议为IEnumerable实现这一点 public static IEnumerable<T> TopWithTies<T, TResult>(this IEnumerable<T> enumerable, Func<T, TResult> selector, int n) { IEnumerable<T> orderedE

在这个问题的基础上,我正在尝试实现一种扩展方法,以在LINQ中为SQL提供TIES功能,我可以按照下面的建议为IEnumerable实现这一点

public static IEnumerable<T> TopWithTies<T, TResult>(this IEnumerable<T> enumerable, Func<T, TResult> selector, int n)
{
    IEnumerable<T> orderedEnumerable = enumerable.OrderByDescending(selector);

    return
    (
        from p in orderedEnumerable
        let topNValues = orderedEnumerable.Take(n).Select(selector).Distinct()
        where topNValues.Contains(selector(p)) // # selector.Invoke(p); could be used aswell
        select p
    );
}
它运行时返回预期结果,但由于使用IEnumerable,我认为执行会立即进行,因此我决定将其转换为IQueryable,以确保延迟执行,如下所示:

public static IQueryable<T> TopWithTies<T, TResult>(this IQueryable<T> queryable, Expression<Func<T, TResult>> selector, int n)
{
    IQueryable<T> orderedList = queryable.OrderByDescending(selector);

    return
    (
        from p in queryable.OrderByDescending(selector)
        let topNValues = queryable.OrderByDescending(selector).Take(n).Select(selector).Distinct()
        where topNValues.Contains(selector(p)) // # Doesn't compile, no .Invoke() method is defined
        select p
    );
}
除了选择器外,一切都好。表达式没有调用方法,不能用作委托

作为Contains方法的参数,我将如何选择用于order by的字段


我被困在这一点上,欢迎任何建议。

我认为这里缺少的链接是选择器从委托更改为表达式的事实

如果你改变主意

where topNValues.Contains(selector(p))


至少它会编译。但在这样做的过程中,我不确定具体实现了什么,因此检查生成的SQL是否如您所期望的那样非常重要。

感谢您在很长时间后回答了一个老问题。用于编译;我从未想过要改变它,以防它表现得像IEnumerable重载。我的意图是确保推迟执行。我担心使用Compile很可能会导致立即执行。无论如何,为了找到答案,我需要试一试。
where topNValues.Contains(selector.Compile()(p))