问题描述
在此过程中,我希望将整个SQL数据库迁移到Cosmos DB 其中一个SQL表列具有如下序列化数据 [{"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
希望它能帮助您。