如何通过Linq过滤一对多关系的查询

时间:2017-05-04 16:38:14

标签: c# .net entity-framework linq one-to-many

我有产品和零件表。这是协会:

Create Table Product
{
   Id int,
   Name nvarchar(max)
}

Create Table Part
{
   Id int,
   Name nvarchar (max),
   ProductID int (foreign key to Product.Id),
   SomeCategoryId int
}

现在,我想返回一个产品列表,其中包含仅包含SomeCategoryId为200的零件清单。

规则:

  • 如果Part.SomeCategoryId<> 200,不包括Part
  • 如果没有Part.SomeCategoryId == 200通过Part.Product.Id与产品对应,请删除整个产品。

如何让我的代码更有效率?

prods = db.Products.OrderBy(o => o.Name).Select(pr => new ProductViewModel
{
    Id = pr.Id,
    Name = pr.Name,
    Parts = pr.Parts.OrderBy(o => o.Name).Select(prt => new PartViewModel
    {
        Id = prt.Id,
        Name = prt.Name,
        SomeCategoryId = prt.SomeCategoryId
    }).Where(w => w.SomeCategoryId == 200).ToList()
}).ToList();

foreach(var prod in prods)
{
    var isSomeCategory = false;
    foreach (var part in prod.Parts)
    {
        if (part.SomeCategoryId == 200)
        {
            isSomeCategory = !isSomeCategory;
        }
    }

    if (isSomeCategory == false)
    {
        prods.Remove(prod);
    }
}

1 个答案:

答案 0 :(得分:3)

怎么样......

prods = db.Products.Where(pr => pr.Parts.Any(p => p.SomeCategoryId == 200)).OrderBy(o => o.Name).Select(pr => new ProductViewModel
{
    Id = pr.Id,
    Name = pr.Name,
    Parts = pr.Parts.OrderBy(o => o.Name).Select(prt => new PartViewModel
    {
        Id = prt.Id,
        Name = prt.Name,
        SomeCategoryId = prt.SomeCategoryId
    }).Where(w => w.SomeCategoryId == 200).ToList()
}).ToList();