与林克一起订购



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

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);
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,
                 ...
             };
var temp = db.Orders.Include("OrderItems").Select(q => q.OrderItems.OrderBy(p => 
                     p.sequence)).ToList();

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

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也将正确排序。

var Orders = db.Orders.Include(a => a.OrderItems)
.OrderBy(a => a.OrderItems.sequence).ToList()

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

相关内容

  • 没有找到相关文章

最新更新