2

我与两个实体有一对多关系:

Order:
int OrderId 
string OrderNumber
...

OrderItem:
int ItemId
int sequence
decimal Quantity
...

一个Order有多个OrderItems,我想编写一个 Linq,它返回所有订单及其项目,项目按序列字段排序。如何编写查询,例如以下查询?

Order myOrder = db.Orders.Include("OrderItems").Include("sequence").FirstOrDefault(x => x.OrderId == 3);
4

4 回答 4

2
var result = from a in Order 
             join b in OrderItems
                on a.Id equals b.OrderId
             order by b.sequence
             select new
             {     
                 a.Id,
                 b.sequence,
                 ...
             };
于 2013-01-23T07:27:53.707 回答
2
var temp = db.Orders.Include("OrderItems").Select(q => q.OrderItems.OrderBy(p => 
                     p.sequence)).ToList();
于 2013-01-23T07:30:37.797 回答
1

如果不将结果投影到新类型中,您将无法做到这一点。

var myOrder= db.Orders.Include("OrderItems")
             .Where(x => x.OrderId == 3)  
             .Select(o => new {
                 order = o,
                 orderItems = o.OrderItems.OrderBy(i => i.sequence)
             }).FirstOrDefault();

// Usage
myOrder.order; // Order

myOrder.order.OrderItems; // OrderItems
myorder.orderItems;  // OrderItems alternative

虽然将其投影到新对象中并不理想,但根据这篇博客文章,有一个很好的副作用,现在order.OrderItems您的匿名对象也将被正确排序。

于 2013-01-23T07:51:26.927 回答
-1
var Orders = db.Orders.Include(a => a.OrderItems)
.OrderBy(a => a.OrderItems.sequence).ToList()

我建议使用 lambdas 来避免查询中的魔术字符串。

于 2013-01-23T07:19:40.390 回答