0

I have the following:

Context context = new Context();

var persons = context.Persons.Select(x => new { Name = x.Name });   

var mapper = OrderMapper.For(persons).Add("name", x => x.Name);

var result = persons.OrderByWithMapper(mapper);

Where:

  • persons is of type IQueryable<anonymous>
  • mapper is of type OrderMapper<anonymous>
  • the OrderByWithMapper is the following:

    public static IQueryable<T> OrderByWithMapper<T>(this IQueryable<T> source, OrderMapper<T> mapper) {
       // Method code
    }
    
  • OrderMapper class is the following:

    public class OrderMapper {
      public static OrderMapper<T> For<T>(IEnumerable<T> collection) {
        return new OrderMapper<T>();
      }
    }
    
    public class OrderMapper<T> {
    }
    

But I get an error when trying to create the Result:

 'List<<anonymous type: string Name>>' does not contain a definition for 'OrderByWithMapper'
 and the best extension method overload 'OrderByWithMapper<<anonymous type: 
 string Name>>(IQueryable<<anonymous type: string Name>>, OrderMapper<<anonymous type: string Name>>)' 
 requires a receiver of type 'IQueryable<<anonymous type: string Name>>'

I am not sure what is wrong as the OrderBy method in EntityFramework works fine with anonymous, e.g.:

public static IOrderedQueryable<TSource> OrderBy<TSource, TKey>(this IQueryable<TSource> source, Expression<Func<TSource, TKey>> keySelector);

What should I change in my OrderByWithMapper method to make it work with anonymous types?

Miguel Moura
  • 36,732
  • 85
  • 259
  • 481

1 Answers1

1

Your extension method OrderByWithMapper<T>(this IQueryable<T> source, OrderMapper<T> mapper) expects an IQueryable<T> and an OrderMapper<T>

According to the error message, you are attempting to execute it on a List<<anonymous type: string Name>>

List<T> does not implement IQueryable

Either change your extension method to accept something else (such as IEnumerable) or change your input to provide an IQueryable. See this SO post for more info on the purpose of IQueryable.

Community
  • 1
  • 1
MrZander
  • 3,031
  • 1
  • 26
  • 50