为什么我得到错误的过滤结果?

时间:2019-02-17 06:53:26

标签: c# entity-framework

我正在使用Entity Framework获取ID = 5002的Product实体。每个产品都有一个订单列表。这样我就对订单进行过滤,以仅获得总价大于10.00的订单,但EF向我返回了完整列表。

using (var context = new SuperMarketContext())
{
    var product = context.Product
        .Include(p => p.Orders)
        .Where(p => p.Id == 5002)
        .First();

    context.Entry(product)
        .Collection(p => p.Orders)
        .Query()
        .Where(o => o.Total > 10)
        .Load();

    foreach (var item in product.Orders)
    {
        Console.WriteLine(item);
    }
}

就像我说的那样,它使我所有的Order instad都比10更具挑战性。为什么会这样?

EF Core 1.1.2

.Net Framework 4.6.1

1 个答案:

答案 0 :(得分:0)

如果您已经有了该产品的订单列表,为什么要再次查询数据库?

固定到您的代码:

using (var context = new SuperMarketContext())
{
    var product = context.Product
        .Include(p => p.Orders)
        .Where(p => p.Id == 5002)
        .First();

    var filteredOrders = context.Entry(product)
        .Collection(p => p.Orders)
        .Query()
        .Where(o => o.Total > 10)
        .Load();

    foreach (var item in filteredOrders)
    {
        Console.WriteLine(item);
    }
}

我的建议:

选项1:

using (var context = new SuperMarketContext())
{
    var product = context.Product
        .Include(p => p.Orders)
        .Where(p => p.Id == 5002)
        .First();

    var orders = product.Orders.Where(o => o.Total > 10).ToList();

    foreach (var item in orders)
    {
        Console.WriteLine(item);
    }
}

选项2:

using (var context = new SuperMarketContext())
{
    var product = context.Product
        .Include(p => p.Orders)
        .Where(p => p.Id == 5002 && p.Orders.Where(t => t.Total > 10))
        .First();

    foreach (var item in product.Orders)
    {
        Console.WriteLine(item);
    }
}

让我知道这些方法是否可行:)