我正在将实体对象转换为我自己的模型(CustomerModel和OrderModel)。如何使用LINQ to Entities(使用变换)返回嵌套数据集?
我现在有一个返回我的客户一个IQueryable方法:
IQueryable<CustomerModel> GetCustomers()
{
return from c in entities.Customers
select new CustomerModel {
CustomerId = c.CustomerId,
CustomerName = c.CustomerName
// Orders = ??
};
}
在我CustomerModel,你可以看到我有订单的数组。
class CustomerModel {
public int CustomerId { get; set; }
public string CustomerName { get; set; }
public OrderModel[] Orders { get; set; }
}
class OrderModel {
public int OrderId { get; set; }
public int CustomerId { get; set; }
public string OrderDetails { get; set; }
}
我似乎无法弄清楚订单类型为Array时,如何设置Customer对象内部的Orders。
当我将CustomerModel的订单更改为IEnumerable而不是数组,并且不能将.ToArray()与LINQ to Entities一起使用时,我能够做到这一点,所以我被卡住了。
所以我的问题是:这是可能做的使用阵列的订单?
问题的答案:
- 为什么一个数组?我在其他地方返回一个数组(供其他项目使用),并且订单也是一个数组也是有意义的。
此外,您不能对订单使用ToArray的(),将引发此错误:
System.NotSupportedException: LINQ to Entities does not recognize the method 'Proj.Models.Orders[] ToArray[Orders](System.Collections.Generic.IEnumerable`1[Proj.Models.Orders])' method, and this method cannot be translated into a store expression.
为什么你想要一个数组?首先,您可以使用Enumerable或Queryable中的.ToArray(),但数组意味着L2E难以跟踪的事情(如排序和可变性)。 – 2012-01-12 00:37:35