【问题标题】:LINQ Query to retrieve itemsLINQ 查询以检索项目
【发布时间】:2012-10-22 07:50:10
【问题描述】:
所以我使用的是 EF,我有以下实体:
Website
Sector
Product
Attribute
AttributeTag
关系如下:
我需要检索未直接链接到表的内容。例如需要Sector 对象的产品,以便使用sector.Products 等内容仅检索特定的Products。
但是如果我需要检索给定Website 下的所有Products 而不是它的父Sector 怎么办?
在我的具体情况下,我的问题是:
1)我如何检索给定特定website_id的所有产品-(不考虑部门)
2)如何检索具有特定tag_id + website_id 的所有产品。 (同时检索它对应的Attribute)
感谢您的帮助。谢谢!
【问题讨论】:
标签:
c#
asp.net
sql
linq
entity-framework
【解决方案1】:
假设你有两个侧边导航属性:
您将在产品实体中拥有List<Sector> SectorList。
您将在 Sector Entity 中拥有一个 List<Product> ProductList。
(sectors_products 不会作为实体出现,因为它在对象世界中不需要)。
您将在 Sector Entity 中拥有 Website Website
您将在产品实体中有一个List<AttributeTag> AttributeTagList;
(products_tags 不会作为实体出现,因为它在对象世界中不需要)。
1) 类似:
var result = ProductEntities
.Where(p => p.SectorList
.Any(s => s.WebSite.Id == <your_website_id>)
);
2) 类似(以 1) 作为基本查询)
result = result
.Where(p => p.AttributeTagList
.Any(at => at.Id == <your_tag_id>)
);
或多合一
var result = ProductEntitites
.Where(p =>
p.SectorList.Any(s => s.WebSite.Id == <your_website_id>) &&
p.AttributeTagList.Any(at => at.Id == <your_tag_id>)
);
【解决方案2】:
架构中的关系形成了一条路径。如果您想弄清楚两个实体集之间的关系,您必须遵循该路径并查询其间的所有实体。
var part1 = (from w in Websites
from s in Sectors
from p in s.Products
where s.Website equals w
&& w.website_id equals web_id
select p).Distinct();
var part2 = from p in part1
let attr = p.Attributes.Where(a => a.tag_id + web_id == target_val)
where attr.Any()
select new { p, attr };
如果我正确理解您的架构,那应该会提取数据来回答您问题的两个部分。