Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cannot convert lambda expression to type 'string' because it is not a delegate type - OrderBy and DbGeography by ref

Tags:

c#

linq

This fails with an error:

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

This runs fine

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

The difference is my DbGeography is not passed by ref this time.

Any reasons why the .OrderBy( x => x.GeoLocation.Distance( geo ) ); function would throw the following error:

Cannot convert lambda expression to type 'string' because it is not a delegate type

like image 996
Jimmyt1988 Avatar asked Sep 27 '22 11:09

Jimmyt1988


1 Answers

The error you get is caused by funny things the overload resolution of C# is doing... It is trying to resolve your OrderBy to the Dynamic Linq "version" of OrderBy, that accepts a string as a parameter.

In general, a more correct error, and the one you get if you remove the using System.Linq.Dynamic; or if you rewrite the statement to force using Queryable.OrderBy, like:

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

would be Cannot use ref or out parameter 'geo' inside an anonymous method, lambda expression, or query expression. As pointed by rdoubleui, here there is an explanation for that.

like image 76
xanatos Avatar answered Oct 01 '22 04:10

xanatos