【发布时间】:2018-05-01 17:40:33
【问题描述】:
在一个通用抽象基类中,我存储了几个用于排序的表达式:
public Expression<Func<T, string>> OrderByString { get; set; }
public Expression<Func<T, int>> OrderByInt { get; set; }
稍后在泛型基类中使用的get:
if (OrderByString != null)
{
results = results.OrderBy(OrderByString);
}
else if (OrderByInt != null)
{
results = results.OrderBy(OrderByInt);
}
最后其中一个将在派生具体类的构造函数中设置:
this.OrderByString = c => c.CustomerID;
我不喜欢我需要根据我想要 OrderBy 的属性类型使用单独的表达式。 ToString 不适用于该属性,因为 LINQ to Entities 不支持它。我所追求的是一种存储表达式的方法,该表达式可以选择任何要排序的属性,而不管类型如何。
如果我尝试一些更通用的东西,例如:
public Expression<Func<T, object>> Order { get; set; }
无法将类型“System.Int32”转换为类型“System.Object”。 LINQ to Entities 仅支持转换实体数据模型基元类型。
此外,如果我尝试稍微修改一下,这也不起作用:
public Expression<Func<T, string>> Order { get; set; }
this.Order = c => c.OrderID.ToString();
LINQ to Entities 无法识别方法 'System.String ToString()' 方法,并且这个方法不能翻译成store 表达。
【问题讨论】:
-
远射:你试过
Expression<Func<T, object>>吗? -
感谢您的建议。我确实尝试过,但忘了提及。现在更新了问题。
-
无论如何你都不想按字符串形式排序:22 在 3 之前