首页 > 解决方案 > 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);

                      }

标签: c#jsonapiforeach

解决方案


您只发布了一个产品,因为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);
    }      
}       

其他事情

  1. myObjectList已经是一个列表,所以你不需要.ToList()
  2. 有什么用var JsonResult = JsonConvert.SerializeObject(myObjectList);
  3. 关于命名约定的小事:NewProduct如果命名会更好newProduct

推荐阅读