我想将整个SQL数据库迁移到Cosmos DB.in这个过程中,其中一个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文档时,如何避免额外的\?
发布于 2018-07-13 05:56:40
您可以使用Azure函数Cosmos DB触发器处理创建的每个文档。请参阅我的功能代码:
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 -如何解除内部json属性
希望它能帮到你。
https://stackoverflow.com/questions/51307392
复制相似问题