一对多和搜索很多(IQueryable)(linq)

时间:2017-04-13 09:02:43

标签: c# entity-framework linq iqueryable

我的数据库中有这种关系:

Order => historyStatus => Status

Order包含HistoryStatusHistoryStatus的列表,其中包含一个Status

我的使用案例是:使用确定的Order搜索所有Status并获取最新的HistoryStatus(基于日期)

我如何在linq中实体和IQueryable

以下是实体:

public class Order 
{
   public int ID { get; set; }

   public virtual ICollection<HistoryStatusOrder> HistoriesStatusOrder { get; set; }
}

public class HistoryStatusOrder 
{
    public int ID { get; set; }
    public DateTime Date { get; set; }
    public string StatusOrderCode { get; 
    public int  OrderId { get; set; }

    public virtual StatusOrder StatusOrder { get; set; }
    public virtual Order Order { get; set; }
}

public class StatusOrder : IEntityBase<string>
{
    public string ID { get; set; }

    public virtual ICollection<HistoryStatusOrder> HistoriesStatusOrder { get; set; }
}

这是我的Search方法:

// do multiple searches
if (searchOrderVM.OrderNumber != null)
    queryable = queryable.Where(x => x.OrderNumber.ToString().Contains(searchOrderVM.OrderNumber.ToString()));

// Next 
if (searchOrderVM.SelectedOrdersStatus != null)
{
    // Need to return queryable = ....
}

// Next search...
....

// Finally I do .ToList() to launch the query in database.

感谢您的帮助:)

1 个答案:

答案 0 :(得分:2)

这会找到所有Orders,其中HistoryStatusOrder的最新Order具有特定的StatusOrderCode

var results = orders.Where (o => o.HistoriesStatusOrder
    .OrderByDescending (hso => hso.Date)
    .First().StatusOrderCode == "foobar");

(假设每个Order始终至少有一个HistoryStatusOrder

您可以使用其他方式编写此查询以保留IQueryable<Order>

var results = orders
    .Select (o => new {
        Order = o,
        LatestHistoryStatusOrder = o.HistoriesStatusOrder
            .OrderByDescending (hso => hso.Date)
            .First()
    })
    .Where (x => x.LatestHistoryStatusOrder.StatusOrderCode == "foobar")
    .Select (x => x.Order);

foreach(var order in results)
{
    // Here you can access:
    //  order.ID
}

如果您想继续访问LatestHistoryStatusOrder,可以跳过上一个.Select(x => x.Order)声明:

var results = orders
    .Select (o => new {
        Order = o,
        LatestHistoryStatusOrder = o.HistoriesStatusOrder
            .OrderByDescending (hso => hso.Date)
            .First()
    })
    .Where (x => x.LatestHistoryStatusOrder.StatusOrderCode == "foobar");

foreach(var item in results)
{
    // Here you can access:
    //   item.Order.ID
    //   item.LatestHistoryStatusOrder
}