Cosmos DB - CreateDocumentQuery not Deserializing Abstract Type
This helper usually works for me:
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 });}
Now inherit your Entity
class:
public class Entity : SerializableObject<Entity>{ public string Id { get; set; } public string Name { get; set; } public Shape Shape { get; set; }}
and try querying it somehow using 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();