c# - C# Web API 循环只发布一个值
问题描述
我将我的行从 SQL 读入和对象,然后想使用下面的代码将它们发布到 web api。发布了一行,但未发布其他 99 行。对于每个循环,我的代码中是否缺少某些内容?
下面的代码……</p>
using (SqlCommand command = new SqlCommand(query, connection))
{
connection.Open();
List<ProductSQL> myObjectList = new List<ProductSQL>();
var reader = command.ExecuteReader();
if (reader.HasRows)
{
while (reader.Read())
{
ProductSQL myObject = new ProductSQL();
myObject.sku = reader["sku"].ToString();
myObject.title = reader["title"].ToString();
myObject.description = reader["description"].ToString();
myObjectList.Add(myObject);
}
}
var JsonResult = JsonConvert.SerializeObject(myObjectList);
Console.WriteLine(myObjectList);
Console.WriteLine(JsonResult);
/* Program Initialization Now need to see why multiple articles are not*/
Console.WriteLine("Post Articles To API");
HttpResponseMessage response2;
Product NewProduct = new Product();
foreach (ProductSQL product in myObjectList.ToList())
{
NewProduct.sku = product.sku;
NewProduct.title = product.title;
NewProduct.description = product.description;
}
/* Mapping that needs to be autmated between models , Product.cs and ProductSQL.cs */
response2 = await client.PostAsJsonAsync("sites/1/products.json",NewProduct);
if (response2.IsSuccessStatusCode)
{
Uri Product = response2.Headers.Location;
Console.WriteLine(response2);
}
解决方案
您只发布了一个产品,因为PostAsJsonAsync
它是在 foreach 块之外执行的!
将代码放在 foreach 块中应该可以解决您的问题。
foreach (ProductSQL product in myObjectList)
{
Product newProduct = new Product {
sku = product.sku,
title = product.title,
description = product.description,
}
/* Mapping that needs to be autmated between models , Product.cs and ProductSQL.cs */
response2 = await client.PostAsJsonAsync("sites/1/products.json", product);
if (response2.IsSuccessStatusCode)
{
Uri productUri = response2.Headers.Location;
Console.WriteLine(response2);
}
}
其他事情:
- myObjectList已经是一个列表,所以你不需要
.ToList()
- 有什么用
var JsonResult = JsonConvert.SerializeObject(myObjectList);
? - 关于命名约定的小事:
NewProduct
如果命名会更好newProduct
推荐阅读
- reactjs - 反应警告:包含隐藏类型的输入,带有值和默认值 - 如何修复?
- visual-studio - 从 VS2019 运行 Docker 容器的问题
- python-3.x - 计算字符串中的每个字符串
- r - 如何过滤多个日期范围
- python-3.x - Twitter API:如何让查询继续运行?
- google-apps-script - 表单提交后发送电子邮件,计算有问题
- android - 用户配置文件不起作用。仅显示电子邮件
- ios - iOS swift如何通过回调调用Alamofire以获取Viewcontroller中的数据
- python - 有人可以解释一下这个python代码的逻辑吗?
- angularjs - 如果在 ng-repeat 中满足条件,angularjs 会显示一个选项卡