如何在DocumentDB中存储来自子类的数据?

时间:2016-10-12 04:23:18

标签: c# crud azure-cosmosdb

我有一个父类

public class Items{
    public Type FeedType { get; set; }
    public double Rating { get; set; }
}

我有两个这个项目的子类

public class SingleItemResponse : Items
{
    public string Id { get; set; }
}
public class MultipletemResponse : Items
{
    public IEnumerable<string> Ids { get; set; }
}

我已将SingleItemResponses和MultipleItemResponses列表添加到项目列表中。

var list = new List<ItemResponse>();
list.add(single); // assume that single is a object of singleItemResponse
list.add(multiple); // assume that multiple is a object of multipleitem 

我可以返回包含singleItemResponse和multipleItemResponse的所有属性的列表。但是,我想在documentDB中存储和检索它们。问题是当我尝试将它们作为IList存储在DocumentDB中时,它们不保留Single和MultipleFeedItems的值,在这种情况下它是ID或ID。

我想知道如何保存和检索它们,我现在唯一的解决方案就是在ItemResponse中将它们一起添加,但我想知道是否有更好的方法而不填充东西。

1 个答案:

答案 0 :(得分:0)

方法1.保持json层次结构

如果要检索,如果两个派生对象具有可区分的属性,例如IdIds,则可以先在JObject中对其进行比较,然后再创建类型。

string collectionName = "YourCollectionName";
Guid id = Guid.Parse("275319a3-d395-46f2-9370-f3eadf691e03"); // Manually set GUID for test purpose.

Uri documentUri = UriFactory.CreateDocumentUri(DocumentDbDatabaseNameConfig, collectionName, id.ToString());
Uri collectionUri = UriFactory.CreateDocumentCollectionUri(DocumentDbDatabaseNameConfig, collectionName);

// test variables.
var list = new List<Items>();
list.Add(new SingleItemResponse() { Rating = 2.2d, Id = "id" });
list.Add(new MultipletemResponse() { Rating = 2.2d, Ids = new List<string>() { "ids1", "ids2"}});

JObject jInput = new JObject();
jInput.Add("id", id);
jInput.Add("list", JArray.FromObject(list));

// Store data.
var upsertedResult = _documentDbclient.UpsertDocumentAsync(collectionUri, jInput, null, true).Result;

// Read stored data.
var result = _documentDbclient.ReadDocumentAsync(documentUri).Result;

JObject jResult = (dynamic)result.Resource;

JArray jArray = (JArray) jResult["list"];
foreach (var jElement in jArray)
{
    if (jElement["Id"] != null)
    {
        SingleItemResponse single = (SingleItemResponse)jElement.ToObject(typeof(SingleItemResponse));
        // Do your job with single instance.
    }
    else if (jElement["Ids"] != null)
    {
        MultipletemResponse multiple = (MultipletemResponse)jElement.ToObject(typeof(MultipletemResponse));
        // Do your job with multiple instance.
    }
}

另外,插入的数据如下;

{
  "id": "275319a3-d395-46f2-9370-f3eadf691e03",
  "list": [
    {
      "Id": "id",
      "Rating": 2.2
    },
    {
      "Ids": [
        "ids1",
        "ids2"
      ],
      "Rating": 2.2
    }
  ],
  "_rid": "KywuAN7aNQABAAAAAAAAAA==",
  "_self": "dbs/KywuAA==/colls/KywuAN7aNQA=/docs/KywuAN7aNQABAAAAAAAAAA==/",
  "_etag": "\"0000ee05-0000-0000-0000-57ff9ecb0000\"",
  "_attachments": "attachments/",
  "_ts": 1476370121
}

方法2.压缩内联json序列化字符串

此方法得到了this post的提示。根据我的经验,我无法在每个项目中生成包含自己类型的正确序列化结果。但从理论上讲,它可行。

JObject jInput = new JObject();

// Use custom serialize/deserialize setting.
JsonSerializerSettings settings = new JsonSerializerSettings
{
    TypeNameHandling = TypeNameHandling.Auto
};

JArray jArray = JArray.FromObject(list);
string strJson = JsonConvert.SerializeObject(jArray, settings);

jInput.Add("id", id);
jInput.Add("strJson", strJson); // treat json just like strings.

var upsertedResult = _documentDbclient.UpsertDocumentAsync(collectionUri, jInput, null, true).Result;

var result = _documentDbclient.ReadDocumentAsync(documentUri).Result;
JObject jResult = (dynamic)result.Resource;
jResult.ToString().Dump();

List<Items> obj = JsonConvert.DeserializeObject<List<Items>>(jResult["strJson"].Value<string>(), settings);