简体   繁体   中英

Querying Cosmos DB by type property

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM