我有一个简单的数据库,使用EF数据模型来处理。如何使用从方法返回的匿名类型
我的表是这样的:
客户表
- 客户编号
- 客户名称
Orders表
- 的OrderId
- 客户ID FK
- 订购日期
我使用一个辅助类来查询我的模型,并在这个类中,我有以下查询:
public static List<object> GetCustomerOrdersCount()
{
using (OrdersDbEntities context = new OrdersDbEntities())
{
return context.Customers.Select(
c => new
{
CustId = c.CustomerId,
CustName = c.CustomerName,
OrdersCount = c.Orders.Count
}).ToList<object>();
}
}
的唯一回报I型可以用这种方法使用是List<object>
最后我的问题是:如何做我使用从这个查询中收到的数据?
我可以读出的值的唯一方法是通过反射:
List<object> custs = Dal.GetCustomerOrdersCount();
foreach (var customer in custs)
{
var properties = customer.GetType().GetProperties();
foreach (var data in properties)
{
var value = data.GetValue(custs[0], null);
}
}
我不知道是否有更好的方法来做到这一点。
为什么您使用的对象,而不是客户?我假设context.Customers是客户的DbSet? – Maess 2012-04-18 19:31:32
这是我在尝试返回列表时得到的错误:System.Linq。IQueryable '不包含'ToList'的定义和最好的扩展方法重载'System.Linq.ParallelEnumerable.ToList (System.Linq.ParallelQuery )'有一些无效参数 –
Yoav
2012-04-18 19:34:58
请发布代码OrdersDbEntities – Maess 2012-04-18 19:36:37