在将数据插入 Cosmos DB 之前修改数据

Modifying Data before inserting it in Cosmos DB

我在 Azure Function 中执行 HTTP 触发器,它根据条件在 Cosmos Db 中添加或更新数据。插入的数据具有修改日期键(见下文)。我想将此密钥更新为触发 运行 并更新 Cosmos Db 中的记录时的日期。如果无法更新修改日期密钥,那么我更愿意在此处添加一个新密钥,如更新日期并插入当前日期。

我怎样才能做到这一点?

这里是插入数据的代码和结构

public static class Function1
    {
        [FunctionName("Function1")]
        public static async Task<IActionResult> Run(
            [HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = null)] HttpRequest req,            
            ILogger log )
        {
           


            log.LogInformation("C# HTTP trigger function processed a request.");
            bool upsert = bool.Parse(req.Query["upsert"]);
            string cosmosDbKey = "TestDJIWEHLM+4Jw==";
            string cosmosDbInstance = "https://localhost:80761";
            string cosmosDbName = "TestProfiles";
            string cosmosDbCollection = "Profiles";
            Uri CollectionUri = UriFactory.CreateDocumentCollectionUri( cosmosDbName, cosmosDbCollection );
            DocumentClient Client = new DocumentClient( new Uri( cosmosDbInstance ), cosmosDbKey );

            string requestBody = await new StreamReader( req.Body ).ReadToEndAsync();
           

            string responseMessage =  upsert;
               
            var rec = JsonConvert.DeserializeObject( requestBody );
            var obj = JObject.Parse( rec.ToString() );
            if( upsert )
            {
                await Client.CreateDocumentAsync(
                    CollectionUri,
                    obj );
            }
            else
            {
                await Client.UpsertDocumentAsync(
                CollectionUri,
                obj);
            }
          
            
            return new OkObjectResult( responseMessage );
           

        }
    }

我是inserting/Update的Obj是这样的格式:

{
    "id": "Test",
    "Type": "tes",
    "LastModified": "2020-03-29T22:22:25.6016794Z",
    "Tags": `["ta` btest "," tabtest2 "]," Properties ":{}," Categories ":[]," Quality ":{" Level ":0}," System ":{" OSVersion ":{" Platform ":2," ServicePack ":" "," Version ":" 10.0.19042.0 "," VersionString ":" Microsoft Windows NT 10.0.19042.0 "}}," DataSets ":[{" Name ":" DataSet1 "," DataFiles ":[{" Name ":" Readme.txt "," LastModified ":" 2020 - 03 - 29T22: 21: 30.570373Z "," Digest ":{" Hash ":" sAxMlg == "," Length ":5}}]}]," FileStore ":{" Service ":" AZURE "}," _etag ":" \ "0500b9f2-0000-0c00-0000-5f884cba0000\"",
    "Trigger": true,
    "Project": "TDemo",
    "ProjectId": "0mh45lfb.zqr"
}

请求正文:

"{\"id\":\"Test\",\"DocType\":\"REC\",\"LastModified\":\"2020-03-29T22:22:25.6016794Z\",\"Tags\":[\"tabtest\",\"tabtest2\"],\"Properties\":{},\"Categories\":[],\"Quality\":{\"Level\":0},\"System\":{\"OSVersion\":{\"Platform\":2,\"ServicePack\":\"\",\"Version\":\"10.0.19042.0\",\"VersionString\":\"Microsoft Windows NT 10.0.19042.0\"}},\"DataSets\":[{\"Name\":\"DataSet1\",\"DataFiles\":[{\"Name\":\"Readme.txt\",\"LastModified\":\"2020-03-29T22:21:30.570373Z\",\"Digest\":{\"Hash\":\"sAnyGxMlg==\",\"Length\":5}}]}],\"FileStore\":{\"Service\":\"AZURE\"},\"_etag\":\"\\"0500b9f2-0000-0c00-0000-5f884cba0000\\"\",\"Trigger\":true,\"Project\":\"Test\",\"ProjectId\":\"0mh45lfb.zqr\"}"
            

你可以通过 Newtonsoft.Json:

 public static class Function1
    {
        [FunctionName("Function1")]
        public static async Task<IActionResult> Run(
            [HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = null)] HttpRequest req,
            ILogger log)
        {
            log.LogInformation("C# HTTP trigger function processed a request.");
            bool upsert = bool.Parse(req.Query["upsert"]);
            string cosmosDbKey = "TestDJIWEHLM+4Jw==";
            string cosmosDbInstance = "https://localhost:80761";
            string cosmosDbName = "TestProfiles";
            string cosmosDbCollection = "Profiles";
            Uri CollectionUri = UriFactory.CreateDocumentCollectionUri(cosmosDbName, cosmosDbCollection);
            DocumentClient Client = new DocumentClient(new Uri(cosmosDbInstance), cosmosDbKey);

            string requestBody = await new StreamReader(req.Body).ReadToEndAsync();


            string responseMessage = upsert;

            var rec = JsonConvert.DeserializeObject<DBObject>(requestBody);
            rec.LastModified = DateTime.UtcNow;
            var obj = JObject.Parse(rec.ToString());

            if (upsert)
            {
                await Client.CreateDocumentAsync(
                    CollectionUri,
                    obj);
            }
            else
            {
                await Client.UpsertDocumentAsync(
                CollectionUri,
                obj);
            }


            return new OkObjectResult(responseMessage);


        }

        public class DBObject
        {
            public string id { get; set; }
            public string Type { get; set; }
            public DateTime LastModified { get; set; }
            public string[] Tags { get; set; }
            public string Project { get; set; }
            public string ProjectId { get; set; }
        }

    }

建议(不是您问题答案的一部分):不要在 Azure 函数的请求正文中取 LastModified 值。您应该始终更改数据访问层的 DateTime(CDC - 更改数据捕获)值。