OrderBy Linq.Expression as parameter =(Of Func(Of T,IComparable))执行LinqToEntity不起作用

时间:2012-04-04 15:21:14

标签: vb.net linq entity-framework-4 lambda

我想让这个工作:

DBSet构造函数:

dbset = DataContext().[Set](Of T)()

呼叫:(计数和页面用于分页,因此对于前20个值,Count = 20和Page = 1)。排序应按名称

LeverancierService.GetLeveranciers(Function(el) el.Name, Count, Page)

c#中的等价物:     LeverancierService.GetLeveranciers(el => el.Name,Count,Page)

给出错误的方法(上面显示的参数):

 Public Overridable Function GetAllPaged(orderby As Expression(Of Func(Of T, IComparable)), ByVal Count As Integer, ByVal Page As Integer) As IEnumerable(Of T)
      Return dbset.OrderBy(orderby).Skip((Page - 1) * Count).Take(Count).ToList()
 End Function

已经尝试将其更改为此,但它也会出现同样的错误:

 Public Overridable Function GetAllPaged(Of TOrderBy)(orderby As Expression(Of Func(Of T, TOrderBy)), ByVal Count As Integer, ByVal Page As Integer) As IEnumerable(Of T)
        Return dbset.OrderBy(orderby).Skip((Page - 1) * Count).Take(Count).ToList()
 End Function

错误:

 Unable to cast the type 'System.String' to type 'System.IComparable'. LINQ to Entities only supports casting Entity Data Model primitive types.

知道怎么做吗?

额外信息:

我在DDD分层应用程序中,所以参数应该保持不变,因为被调用的方法是一个被覆盖的接口(例如,如果我改变它,我必须这样做200次左右,因为它在VB.Net而不是C#(= 1更改))

1 个答案:

答案 0 :(得分:1)

这是我的样本。我希望它能解决你的问题:

如果未定义 dbset的类型

Public Function Test(Of TEntity As Class, TKey) _
    (keySelector As Expression(Of Func(Of TEntity, TKey))) As IList(Of TEntity)
    Return DataContext.Set(Of TEntity).OrderBy(keySelector).ToList
End Function

用法:

Repository.Test(Function(obj As MyEntity) obj.Name)

如果 dbset的类型已定义,您可以使用其他示例:

    Public Function Test2(Of TKey) _
        (keySelector As Expression(Of Func(Of MyEntity, TKey))) _
        As IList(Of MyEntity)
        Return DataContext.Set(Of MyEntity).OrderBy(keySelector).ToList
    End Function

像这样使用:

Repository.Test(Function(obj) obj.Name)