OrderBy与匿名类型

时间:2017-05-10 15:48:04

标签: c# entity-framework entity-framework-core c#-7.0

我有以下内容:

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

其中:

  • 人员属于IQueryable<anonymous>
  • mapper的类型为OrderMapper<anonymous>
  • OrderByWithMapper如下:

    public static IQueryable<T> OrderByWithMapper<T>(this IQueryable<T> source, OrderMapper<T> mapper) {
       // Method code
    }
    
  • OrderMapper课程如下:

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

但是在尝试创建结果时出现错误:

 '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>>'

我不确定有什么问题,因为EntityFramework中的OrderBy方法适用于匿名,例如:

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

我应该在OrderByWithMapper方法中更改什么才能使其与匿名类型一起使用?

1 个答案:

答案 0 :(得分:1)

您的扩展程序方法OrderByWithMapper<T>(this IQueryable<T> source, OrderMapper<T> mapper)需要IQueryable<T>OrderMapper<T>

根据错误消息,您试图在List<<anonymous type: string Name>>

上执行它

List<T>未实施IQueryable

更改您的扩展程序以接受其他内容(例如IEnumerable)或更改您的输入以提供IQueryable。有关IQueryable目的的更多信息,请参阅this SO post