0

In my project i want to add inheritance for some classes and save the generated objects to a documentcollection in the Cosmos DB database. To save the information about the type i use this preference in JSON.net: https://www.newtonsoft.com/json/help/html/SerializeTypeNameHandling.htm

But how can i query the collection by type without retriving all documents with LINQ in a typesafe way. The best would be to add a property to those classes named for example Type which contains the information of the "$type" property of the JSON Object. Then i can query something like this:

       return Client.CreateDocumentQuery<TEntity>(DocumentCollectionUri).Where(entity => entity.Type == typeof(Car).ToString());

This LINQ Query would be translated to SQL and then sent to the server. I only get back those objects of type car. This would be the optimum, is something like this possible and fast?

Niklas Raab
  • 1,576
  • 1
  • 16
  • 32

1 Answers1

3

All you need it your TEntity property to implement an interface of some sort, lets way ICosmosEntity which has an EntityType property which is a string.

Then all your TEntity objects will need to implement this interface and they will set the nameof(TEntity) as the EntityType.

That way you can have your queryable look like this: return Client.CreateDocumentQuery<TEntity>(DocumentCollectionUri).Where(entity => entity.EntityType == nameof(Car)) which will return exactly what you need.

If you get stuck then I would recommend you check how collection sharing works in Cosmonaut. Sounds like exactly something you need.

Disclaimer: I am the creator of Cosmonaut.

Nick Chapsas
  • 6,872
  • 1
  • 20
  • 29