0

我想構建一個IQueryable的擴展方法,它接受一個排序方向作爲參數。我希望能夠將此方法應用於帶有EF的SQL服務器查詢。以下是我迄今爲止:尋找linq到SQL通用函數的適當返回類型

public static class QueryableExtensions 
{ 
    public static IOrderedQueryable<T> ApplyOrdering<T>(this IQueryable<T> source, Expression<Func<T, Object>> lambda, bool ascending) 
    { 
     return ascending ? source.OrderBy(lambda) : source.OrderByDescending(lambda); 
    } 
} 

我有以下驅動程序代碼:

[Table("TestTable")] 
public partial class TestTable 
{ 
    [Key] 
    public int IntVal { get; set; } 
} 

public partial class Model1 : DbContext 
{ 
    public Model1() 
     : base("name=Model1") 
    { 
    } 

    public virtual DbSet<TestTable> TestTables { get; set; } 
} 

class Program 
{ 
    private static void Main(string[] args) 
    { 
     var context = new Model1(); 
     var baseQuery = from entity in context.TestTables 
          select entity; 

     var sortedByInt = baseQuery.ApplyOrdering(x => x.IntVal, true).ToList(); 
    } 
} 

然而,運行此代碼將導致以下錯誤:

Unable to cast the type 'System.Int32' to type 'System.Object'. LINQ to Entities only supports casting EDM primitive or enumeration types.

是否有解決?我懷疑我需要一個替代返回類型的表達式。

回答

1

嘗試:

public static class QueryableExtensions 
{ 
    public static IOrderedQueryable<T> ApplyOrdering<T, TProp>(this IQueryable<T> source, Expression<Func<T, TProp>> lambda, bool ascending) 
    { 
     return ascending ? source.OrderBy(lambda) : source.OrderByDescending(lambda); 
    } 
}