错误代码:
var orders = db.Orders.Where(o => o.UserId == userid).Select(c =>
new Order
{
OrderId = c.OrderId,
OrderDate = c.OrderDate,
Total = c.Total,
OrderDetails = db.OrderDetailss.Where(od => od.OrderId == c.OrderId).ToList()
}
).ToList();
正确代码:
var orders = db.Orders.Where(o=>o.UserId==userid).ToList().Select
(c =>
new Order
{
OrderId = c.OrderId,
OrderDate = c.OrderDate,
Total = c.Total,
OrderDetails = db.OrderDetailss.Where(od => od.OrderId == c.OrderId).ToList()
}
).ToList();
原理: linq 选择数据时候 不能new 已知的对象,只能匿名的。 但是如果从一个 List 列表 就可以new 已知的类。
昂首阔步,不留一点遗憾