【发布时间】:2015-08-17 14:15:53
【问题描述】:
在尝试将属性值检索为对象而不是它们各自的类型时,我遇到了一些麻烦。以下代码抛出此异常:
Unable to cast the type 'System.DateTime' to type 'System.Object'. LINQ to Entities only supports casting EDM primitive or enumeration types.
此代码在选择字符串时可以正常工作,但在选择 DateTimes、Integers 或 Nullable 类型时则不行。
public class Customer
{
public int Id { get; set; }
public string Name { get; set; }
public DateTime CreatedOn { get; set; }
}
public class Program
{
public static void Main(string[] args)
{
using (var ctx = new MyContext())
{
// Property selector: select DateTime as Object
Expression<Func<Customer, object>> selector = cust => cust.CreatedOn;
// Get set to query
IQueryable<Customer> customers = ctx.Set<Customer>();
// Apply selector to set. This throws:
// 'Unable to cast the type 'System.DateTime' to type 'System.Object'. LINQ to Entities only supports casting EDM primitive or enumeration types.'
IList<object> customerNames = customers.Select(selector).Distinct().ToList();
}
}
}
public class MyContext : DbContext
{
}
最终目标是进行通用过滤,以从对象的任何属性中选择不同的值。
【问题讨论】:
-
你终于调用了
ToList,那为什么不在那之后将 DateTime 转换为对象呢? -
因为选择器成员表达式是在运行时创建的,所以在编译时属性类型是未知的。我可以使用反射来确定类型,但这对于嵌套属性会很复杂
标签: c# linq entity-framework linq-to-entities