gpt4 book ai didi

c# - Cosmos DB - CreateDocumentQuery 不反序列化抽象类型

转载 作者:行者123 更新时间:2023-11-30 12:55:33 25 4
gpt4 key购买 nike

我正在尝试让 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 属性,并且检索文档工作正常。仅当我尝试查询引发异常的文档时。关于如何让它发挥作用的任何想法?

关于如何最好地处理抽象类型还有其他建议吗?我有一个相当深的对象图,其中包含多层抽象类型。

最佳答案

这个助手通常对我有用:

public abstract class SerializableObject<T>
{
public static T FromJObject(JObject jObject) =>
Parse($"{jObject}");

public static T Parse(string json) =>
JsonConvert.DeserializeObject<T>(json,
new JsonSerializerSettings
{
TypeNameHandling = TypeNameHandling.Objects
});

public JObject ToJObject() => JObject.Parse(ToJson());

public string ToJson() =>
JsonConvert.SerializeObject(this, Formatting.Indented,
new JsonSerializerSettings
{
TypeNameHandling = TypeNameHandling.Objects
});
}

现在继承您的 Entity 类:

public class Entity : SerializableObject<Entity>
{
public string Id { get; set; }
public string Name { get; set; }
public Shape Shape { get; set; }
}

并尝试使用 JObject 以某种方式查询它:

var result = client.CreateDocumentQuery<JObject>(
UriFactory.CreateDocumentCollectionUri(database, collection),
new FeedOptions() { MaxItemCount = 1 })
.Where(x => x.Id == entity.Id)
.AsEnumerable()
.Select(Entity.FromJObject)
.FirstOrDefault();

关于c# - Cosmos DB - CreateDocumentQuery 不反序列化抽象类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48275170/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com