【发布时间】:2018-01-16 06:22:33
【问题描述】:
我正在尝试让 Cosmos DB .NET SDK v1.19.1 使用 Json.net 序列化设置自动将对象反序列化为正确的类型。除了查询文档时,这似乎工作正常。以如下代码为例:
public abstract class Shape
{
public int Area { get; set; }
}
public class Square : Shape { }
public class Triangle : Shape { }
public class Entity
{
public string Id { get; set; }
public string Name { get; set; }
public Shape Shape { get; set; }
}
static void Main(string[] args)
{
JsonConvert.DefaultSettings = () => new JsonSerializerSettings()
{
ContractResolver = new CamelCasePropertyNamesContractResolver(),
TypeNameHandling = TypeNameHandling.Auto
};
var database = "db";
var collection = "coll";
var client = new DocumentClient(new Uri("https://docdburi.documents.azure.com:443/"), "supersecretkey", JsonConvert.DefaultSettings());
var entity = new Entity() { Id = "testid", Name = "John Doe", Shape = new Square() { Area = 5 } };
var doc = client.CreateDocumentAsync(UriFactory.CreateDocumentCollectionUri(database, collection), entity).Result;
entity = client.ReadDocumentAsync<Entity>(UriFactory.CreateDocumentUri(database, collection, entity.Id)).Result;
// all good so far ... next line throws serialization exception on abstract shape type
var result = client.CreateDocumentQuery<Entity>(UriFactory.CreateDocumentCollectionUri(database, collection), new FeedOptions() { MaxItemCount = 1 })
.Where(x => x.Id == entity.Id).AsDocumentQuery()
.ExecuteNextAsync<Entity>().Result;
文档在 Cosmos DB 中创建,形状上的 $type 属性符合预期,并且检索文档工作正常。只有当我尝试查询引发异常的文档时。关于如何让它发挥作用的任何想法?
关于如何最好地处理抽象类型还有其他建议吗?我有一个包含多层抽象类型的相当深的对象图。
【问题讨论】:
标签: c# json azure-cosmosdb