【问题标题】:Cannot convert lambda expression to type 'string' because it is not a delegate type - OrderBy and DbGeography by ref无法将 lambda 表达式转换为类型“字符串”,因为它不是委托类型 - OrderBy 和 DbGeography by ref
【发布时间】:2015-06-29 09:53:29
【问题描述】:

这会失败并出现错误:

private IQueryable<Field> PrepareAllFieldsQuery( ref DbGeography geo, int page, int amount, string sort, string order, ISearchCriteria searchCriteria )
{
    var query = this.context.Fields
                            .Where( x => x.DeletedAt == null )
                            .OrderBy( x => x.GeoLocation.Distance( geo ) );
    ...
}

运行良好

private IQueryable<Field> PrepareAllFieldsQuery( DbGeography geo, int page, int amount, string sort, string order, ISearchCriteria searchCriteria )
{
    var query = this.context.Fields
                            .Where( x => x.DeletedAt == null )
                            .OrderBy( x => x.GeoLocation.Distance( geo ) );
    ...
}

不同的是我的DbGeography这次没有被ref传递。

.OrderBy( x =&gt; x.GeoLocation.Distance( geo ) ); 函数会抛出以下错误的任何原因:

无法将 lambda 表达式转换为类型“字符串”,因为它不是委托类型

【问题讨论】:

  • 我什至无法编译它... 不能在匿名方法、lambda 表达式或查询表达式中使用 ref 或 out 参数 'geo'
  • 这可能post 似乎有解释。
  • @rdoubleui - 这很有意义。谢谢你。

标签: c# linq


【解决方案1】:

你得到的错误是由 C# 的重载解析正在做的有趣的事情引起的......它试图将你的 OrderBy 解析为 OrderBy 的动态 Linq“版本”,它接受 string 作为一个参数。

一般来说,这是一个更正确的错误,如果您删除 using System.Linq.Dynamic; 或重写语句以强制使用 Queryable.OrderBy,您会得到一个错误,例如:

var query = Queryable.OrderBy( this.context.Fields.Where( x => x.DeletedAt == null ),
                               x => x.GeoLocation.Distance( geo ) );

将是不能在匿名方法、lambda 表达式或查询表达式中使用 ref 或 out 参数“geo”。正如 rdoubleui 所指出的,here 对此有解释。

【讨论】:

  • 感谢您的回答!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多