【问题标题】:Unable to Find out Foreign Key related values without duplication无法在不重复的情况下找出外键相关值
【发布时间】:2017-08-03 03:05:19
【问题描述】:

我正在尝试获取单个产品的所有图像和项目符号点。图片和 Bullet_Points 有外键 Product_ID 供参考。但是,即使我只有 8 个 bullet_points ,单个产品的 5 个图像,我总共得到 40 行。我做错了什么?

下面是我正在执行的 linq 查询。

from p in Products
from i in Images
from s in Specifications
where p.ProductID==i.Product_ID && p.ProductID==5002
where p.ProductID==s.Product_ID && p.ProductID==5002
select new  { p.ProductID,i.Image_URL,s.Bullet_Point}

【问题讨论】:

  • 您希望在单个查询中同时接收 ImagesSpecifications。这导致关系乘法,因此记录数变为8 * 5 = 40。尝试进行 2 个单独的查询,一个用于 Images,另一个用于 Specifications
  • 也许您只想获取Product 的一条记录以及ImagesSpecifications 的两个相关集合?
  • 是的,你是对的。一个产品有多个图像和多个子弹点与外键绑定。我可以在一个查询中检索所有这些而不重复。@IvanGritsenko 或者我应该更改建筑?
  • @Arun3x3 架构和您的查询一样好。您只是无法在一个请求中得到您想要的。一张表只有 2 个维度,因此您的查询结果完全符合 Ivan Gritsenko 的解释。如果您删除重复的条目,您将丢失图像信息。所以实际上没有重复的行。所以这里两个查询是最好的解决方案。
  • 感谢您的回复@Sebi。我可以将其安排在两个查询中,但问题在于要查看的模型的上下文中。我如何将两个查询作为一个视图对象发送到视图,因为我想传递信息以便可以显示和编辑它。

标签: c# linq linq-to-sql asp.net-mvc-5


【解决方案1】:

尝试以下查询:

from p in Products
join i in Images on i.Product_ID equals p.ProductID into imgs
join s in Specifications on s.Product_ID equals p.ProductID into specs
where p.ProductID == 5002
select new { p.ProductID, 
    urls = imgs.Select(x => x.Image_URL), 
    bulletPoints = specs.Select(x => x.Bullet_Point) };

为什么不使用Product 的导航属性?我可以看到您的 Product 模型具有 ImagesSpecifications 属性。所以你也可以试试:

Products.Where(p => p.ProductID == 5002).Select(p => new { 
    p.ProductID, 
    urls = p.Images.Select(x => x.Image_URL), 
    bulletPoints = p.Specifications.Select(x => x.Bullet_Point) })

【讨论】:

    猜你喜欢
    • 2015-01-23
    • 2011-10-31
    • 1970-01-01
    • 2013-12-12
    • 1970-01-01
    • 1970-01-01
    • 2010-10-21
    • 1970-01-01
    • 2018-01-23
    相关资源
    最近更新 更多