【发布时间】:2018-08-25 15:41:24
【问题描述】:
我的 SQL Server 数据库中有以下 3 个表定义:
+----------------------------------+-----------------+------------------------------------------------
| Product | Rating | Image |
+----------------------------------+-----------------+-------------------------------------------------
| ProductId | Id | Id |
| ProdctName | Rating | Image |
| | ProductId FK References(Product)| ProductId FK References(Product)|
+----------------------------------+-----------------+---------------+----------------------------------
这些表包含以下示例数据:
+----------------------------------+------------
|Product | ProductId |ProductName |
+----------------------------------+------------
| | 1 |Prodcuct 1 |
| | 2 |Prodcuct 2 |
| | 3 |Prodcuct 3 |
| | 4 |Prodcuct 4 |
+----------------------------------+------------+
+----------------------------------+----------------------+
|Rating | Id |RatingVal |ProductId |
|+----------------------------------+-----------------------
| | 1 |3 |1 |
| | 2 |2 |2 |
| | 3 |3 |2 |
| | 4 |5 |3 |
| | 5 |4 |3 |
+---------------------+------------+------------+----------+
+----------------------------------+----------------------+
|Image | Id |ImagePath |ProductId
+----------------------------------+-----------------------
| | 1 |ABC |1 |
| | 2 |XYZ |2 |
| | 3 |LMN |3 |
| | 4 |PQR |4 |
+---------------------+------------+------------+----------+
我需要在一个地方收集有关产品的信息,以便每个产品都包含有关产品的详细信息(来自产品表)、相关的平均评分(来自评分表)m 和产品的图像路径(来自图像表)。换句话说,我需要以下输出:
+----------------------------------+--------------------------------+
|Output | ProductId |ProductName |Avg(Rating)|ImgPath|
+----------------------------------+--------------------------------+
| | 1 |Prodcuct 1 |3 |ABC |
| | 2 |Prodcuct 2 |2.5 |XYZ |
| | 3 |Prodcuct 3 |4.5 |LMN |
| | 4 |Prodcuct 4 |0.0 |PQR |
+----------------------------------+------------+-----------+-------+
我正在使用实体框架来获取这些数据,以及我的代码中上下文类中的实体(如下所示)。
我的问题是:如何为所有产品生成我想要的输出。 我下面的代码无法获得我想要的所有数据。问题是结果中没有显示 id4 的产品,我认为这是因为产品 4 在评级表中没有条目。
var trendingProducts = (from ratings in entities.Rating
group ratings by new { ratings.productId } into c
join products in entities.Products on c.FirstOrDefault().productId equals products.ProductID
join images in entities.Images on c.Key.productId equals images.ProductId
select new ProductViewModel
{
ProductId = products.ProductId,
ProductName = products.ProductName,
RatingVal = c.Average(l => l.RatingVal) == null ? 0 : c.Average(l => l.Rating),
ImagePath = images.ImagePath,
}).ToList();
【问题讨论】:
-
能否请您也发布您收到的错误消息?谢谢
-
嗨 PiJei 感谢您的关注,我没有收到任何错误或异常,但是我没有得到不包含产品 4 详细信息的所需输出
-
我刚刚注意到,在您的评级表中,您没有产品 id 4 的条目,这可能是原因。
-
是的,您是对的,对于该产品,我需要在输出结果中提到的评级为 0.0
-
那么你需要一个完整的外连接来保留所有键,而不是进行内连接,
标签: c# sql-server entity-framework linq