Jimmyt1988
Jimmyt1988

Reputation: 21156

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

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

Upvotes: 5

Views: 4283

Answers (1)

xanatos
xanatos

Reputation: 111890

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.

Upvotes: 4

Related Questions