我有产品和零件表。这是协会:
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的零件清单。
规则:
如何让我的代码更有效率?
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);
}
}
答案 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();