如何编写涉及多对多表的最小 linq 查询?
Product
和 ProductCategory
表通过多对多表 ProductToCategory
“连接”。
对于某些具有某个 ID 的产品(让我们将其标记为 product_1),我需要获取与 product_1 相同类别的下一个产品。
我想用 one 查询来完成此操作,因此以下查询可以完成工作,但 sql-profiler 显示非常巨大的查询。有什么建议如何重写查询吗?
(from p in cxt.Products
join c in cxt.ProductToCategories on p.Id equals c.ProductId
where p.Id > id && c.CategoryId == (from p2 in cxt.Products
join c2 in cxt.ProductToCategories on p.Id equals c.ProductId
where p2.Id == id
select c2.CategoryId).FirstOrDefault()
orderby p.Id
select p).FirstOrDefault();
Product
and ProductCategory
tables are "connected" via many-to-many table ProductToCategory
.
For some product with some id(let's mark it as product_1) I need to get the next product of the same category as the product_1.
I wanted to do this with one query, so the following query does the work but the sql-profiler shows very HUGE query. Are there any suggestions how rewrite the query?
(from p in cxt.Products
join c in cxt.ProductToCategories on p.Id equals c.ProductId
where p.Id > id && c.CategoryId == (from p2 in cxt.Products
join c2 in cxt.ProductToCategories on p.Id equals c.ProductId
where p2.Id == id
select c2.CategoryId).FirstOrDefault()
orderby p.Id
select p).FirstOrDefault();
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
注意:我想什么时候说
真正的意思是
Note: I suppose that when is said
what really means is
我建议您在数据库中创建一个名为 NextProductInCategory 的视图,然后使用简单的 linq 查询来检索您想要的内容。
I suggest you create a view in the database called NextProductInCategory and then have a simple linq query to retrieve what you want.