动态OrderBy因可空列而失败

时间:2013-01-19 18:21:26

标签: c# linq dynamic nullable

有一个表Customers,其中包含可以为cstCredit列的可居住用户。以下工作正常,可以迭代。

var query = _oContext.Customers.OrderBy(cst => cst.cstCredit);

但是,迭代时会出现以下情况。

public IQueryable<Customer> AllSorted(Expression<Func<Customer, object>> orderby)
{
   return _oContext.Customers.OrderBy(orderby);
}

void test()
{
   var query = AllSorted(cst => cst.cstCredit);
   foreach (Customer oCustomer in query)
   {
   }
}

消息(翻译自德语)是

  

“System.Nullable类型无法转换为System.Object.LINQ   to Entities仅支持转换原语或枚举类型“。

我做错了什么?

2 个答案:

答案 0 :(得分:1)

尝试编写AllSorted方法,如下所示:

public IQueryable<Customer> AllSorted<TKey>(Expression<Func<Customer, TKey>> orderby)
{
   return _oContext.Customers.OrderBy(orderby);
}

它不起作用,因为像int?这样的可空类型是值类型不是从对象派生的(并且是System.Nullable结构的实例),因此Expression<Func<Customer, object>> orderby不适用于它们。

答案 1 :(得分:0)

试试这个

public IQueryable<Customer> AllSorted<T>(Expression<Func<Customer, T>> orderby)
{
   return _oContext.Customers.OrderBy(orderby);
}
相关问题