如何避免SQLDatabase到Cosmos DB数据迁移中的转义字符 [英] How to avoid escape character in Migrating the data from SQLDatabase to Cosmos DB
本文介绍了如何避免SQLDatabase到Cosmos DB数据迁移中的转义字符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
[{"Id":"1","Type":"Phone","HeaderLabel":"HQ - Main Line","ContactNumber":"+9122222222"}]
序列化数据表示一个类
public class ContactNumber
{
public string ContactNumberId { get; set; }
public string Type { get; set; }
public string HeaderLabel { get; set; }
public string ContactNumber { get; set; }
}
在SQL中保存数据时,我必须对类执行序列化和反序列化,这是必要的。
public string _ContactNumbers { get; set; }
public List<ContactNumber> ContactNumbers
{
get { return _ContactNumbers == null ? null : JsonConvert.DeserializeObject<List<ContactNumber>>(_ContactNumbers); }
set { _ContactNumbers = value == null ? null : JsonConvert.SerializeObject(value); }
}
使用迁移工具后,更新如下
"ContactNumbers":"[{"Id":"1","Type":"Phone","HeaderLabel":"HQ - Main Line","ContactNumber":"+9122222222"}]"
类保持不变。在从COSMOS DB获取数据时,我没有执行任何序列化和反序列化。
public List<ContactNumber> ContactNumbers
获取数据时抛出错误
Error converting value "[{"Id":"1","Type":"Phone","HeaderLabel":"HQ - Main Line","ContactNumber":"+9122222222"}]" to type 'System.Collections.Generic.List`1[CosmosDB.Models.ContactNumber]'. Path 'ContactNumber', line 1, position 2411.
错误是因为迁移后添加的字符串中有额外字符。
我不想序列化和反序列化Cosmos DB中的类,因为这样做是不必要的。
那么,如何避免将数据从SQL数据库迁移到Cosmos DB文档时出现额外的问题?
推荐答案
您可以使用Azure Function Cosmos DB Trigger处理创建的每个文档。请参考我的功能代码:
using System;
using System.Collections.Generic;
using Microsoft.Azure.Documents;
using Microsoft.Azure.Documents.Client;
using Microsoft.Azure.WebJobs;
using Microsoft.Azure.WebJobs.Host;
using Newtonsoft.Json.Linq;
namespace ProcessJson
{
public class Class1
{
[FunctionName("DocumentUpdates")]
public static void Run(
[CosmosDBTrigger(databaseName:"db",collectionName: "item", ConnectionStringSetting = "CosmosDBConnection",LeaseCollectionName = "leases",
CreateLeaseCollectionIfNotExists = true)]
IReadOnlyList<Document> documents,
TraceWriter log)
{
log.Verbose("Start.........");
String endpointUrl = "https://***.documents.azure.com:443/";
String authorizationKey = "***";
String databaseId = "db";
String collectionId = "import";
DocumentClient client = new DocumentClient(new Uri(endpointUrl), authorizationKey);
for (int i = 0; i < documents.Count; i++)
{
Document doc = documents[i];
if((doc.alreadyFormat == Undefined.Value) ||(!doc.alreadyFormat)){
String info = doc.GetPropertyValue<String>("info");
JArray o = JArray.Parse(info);
doc.SetPropertyValue("info", o);
doc.SetPropertyValue("alreadyFormat", true);
client.ReplaceDocumentAsync(UriFactory.CreateDocumentUri(databaseId, collectionId, doc.Id), doc);
log.Verbose("Update document Id " + doc.Id);
}
}
}
}
}
另外,请参考案例:Azure Cosmos DB SQL - how to unescape inner json property
希望它能帮助您。
这篇关于如何避免SQLDatabase到Cosmos DB数据迁移中的转义字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文