【问题标题】:how to iterate array values and update multiple records in C# [closed]如何在 C# 中迭代​​数组值并更新多条记录 [关闭]
【发布时间】:2021-02-11 06:34:14
【问题描述】:

我想根据数组值更新多条记录。 “userid”和“orderid”是用逗号分隔的数组值。我想遍历数组值并更新firestore的记录。用户 ID 和订单 ID 将具有相同的索引。有多少用户,那么多少 orderid 就会有多少。

示例 webapi

https://localhost:44308/AssignTruck/djK2BjrTTnuLSqD8LbeZ,djK2BjrTTnuLSqD8LbeZ/PdTXq6Rk0WfJK9FQV8vt,TmHhOapTNaZco4PcCF8j/S-1

userid - djK2BjrTTnuLSqD8LbeZ,djK2BjrTTnuLSqD8LbeZ
docid -  PdTXq6Rk0WfJK9FQV8vt,TmHhOapTNaZco4PcCF8j

代码

[HttpGet("/AssignTruck/{userid}/{orderid}/{shipid}")]
        public async Task<ActionResult> AssignTruck(string userid, string orderid, string shipid)
        {
            {
                FirestoreDb db = FirestoreDb.Create("trucks");
                DocumentReference docRef = db.Collection("users/" + userid + "/orders").Document(orderid);
                DocumentSnapshot snapshot = await docRef.GetSnapshotAsync();
                Truck truck = null;
                if (snapshot.Exists)
                {
                    truck = snapshot.ConvertTo<Truck>();
                    truck.Docid = snapshot.Id;
                    truck.shipId = shipid;
                }
                else
                {
                }
                await docRef.SetAsync(truck);
                return RedirectToAction("tables");
            }
        }

【问题讨论】:

    标签: c# json google-cloud-firestore webapi


    【解决方案1】:

    假设userids和orderids对应同一个index,你的代码应该如下:

        [HttpGet("/AssignTruck/{userid}/{orderid}/{shipid}")]
        public async Task<ActionResult> AssignTruck(string userid, string orderid, string shipid)
        {
            string[] uIds= userid.Split(',');
            string[] oIds= orderid.Split(',');
    
            for(int i=0; i<uIds.Length(); i++) {              
                FirestoreDb db = FirestoreDb.Create("trucks");
                DocumentReference docRef = db.Collection("users/" + uIds[i] + "/orders").Document(oIds[i]);
                DocumentSnapshot snapshot = await docRef.GetSnapshotAsync();
                Truck truck = null;
                if (snapshot.Exists)
                {
                    truck = snapshot.ConvertTo<Truck>();
                    truck.Docid = snapshot.Id;
                    truck.shipId = shipid;
                }
    
                await docRef.SetAsync(truck);
                
            }
            return RedirectToAction("tables");
        }
    

    【讨论】:

    • 这无法编译(.length() 无效),如果编译成功,for 中的return 会使for 循环毫无意义
    • 感谢您的代码@filissen。我正在尝试这段代码。
    • 感谢@filessen,您的代码运行良好。更改请求是等待 docRef.SetAsync(truck);应该在循环之外并且 .length() 将是 Length
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-19
    • 2022-06-10
    • 2017-08-07
    • 2018-01-17
    • 2021-04-14
    • 2014-06-21
    相关资源
    最近更新 更多