【发布时间】:2021-06-30 12:41:08
【问题描述】:
请在这里帮助我。
我想获取产品的详细信息以及该产品的图片列表。下面的代码工作正常,但它只返回一张产品图片。我在将 MySQL 查询的结果映射到 C# 对象时遇到问题。
这是我迄今为止尝试过的
public ProductModel GetProductDetail(uint product_id)
{
var cmd = this.MySqlDatabase.Connection.CreateCommand() as MySqlCommand;
cmd.CommandText = @"SELECT products.*, images.* FROM products LEFT JOIN images ON products.product_id= images.product_id WHERE products.product_id = @product_id LIMIT 0,1";
cmd.Parameters.AddWithValue("@product_id", product_id);
using (var reader = cmd.ExecuteReader())
while (reader.Read())
{
return new ProductModel()
{
product_id = reader.GetValue<UInt32>("product_id"),
subcategory_id = reader.GetValue<UInt32>("subcategory_id"),
product_name = reader.GetValue<String>("product_name"),
description = reader.GetValue<String>("description"),
is_recent = reader.GetValue<Boolean>("is_recent"),
is_popular = reader.GetValue<Boolean>("is_popular"),
is_available = reader.GetValue<Boolean>("is_available"),
price = reader.GetValue<Decimal>("price"),
overall_rating = reader.GetValue<Double>("overall_rating"),
views = reader.GetValue<UInt32>("views"),
people_rated = reader.GetValue<UInt32>("people_rated"),
date_posted = reader.GetValue<DateTime>("date_posted"),
Images = new List<ImagesModel>
{
new ImagesModel
{
imageurl = reader.GetValue<String>("imageurl"),
created_date = reader.GetValue<DateTime>("created_date")
}
}
};
}
return null;
}
下面也是我得到的 JSON 结果
{
"code": 1,
"message": "Product found",
"document": {
"product_id": 11,
"subcategory_id": 22,
"product_name": "Lead Guitar",
"description": "Unde dolor sed natus velit omnis doloribus consequatur adipisci quos quasi laboriosam optio aut beatae; cupiditate modi animi hic non qui consequatur, natus voluptatem quae ea quia est doloremque possimus.",
"is_recent": true,
"is_popular": false,
"is_available": false,
"price": 1942.51,
"overall_rating": 3,
"views": 520,
"people_rated": 350,
"date_posted": "2005-05-08T06:21:03",
"images": [
{
"imageurl": "http://www.thetehad.es/but/teerted/anne/ionhe.png",
"created_date": "2021-08-28T12:33:01"
},
.
.
.
// THERE SHOULD BE MORE IMAGES HERE BUT I AM GETTING ONLY ONE
]
}
}
请问我在这里做错了什么?非常感谢任何帮助。
【问题讨论】:
-
为什么需要在一次查询中获取产品和图片?对于单个对象在单独查询中更高效地查询自身及其图像,这里不存在选择 N+1 问题。