Vivendi
Vivendi

Reputation: 21007

Query CosmosDB with CosmosClient and map to object

Right now I have the following code to query my CosmosDB:

var streamIterator = containerLogs.GetItemQueryStreamIterator("SELECT * FROM mycontainer");

while (streamIterator.HasMoreResults)
{
    var results = await streamIterator.ReadNextAsync();
    var stream = results.Content;
    using var reader = new StreamReader(stream);
    string data = await reader.ReadToEndAsync();

    // typeof what..?
    //var dbDocuments = JsonConvert.DeserializeObject<???>(data);
}

The variable data will contain the following JSON:

{
    "_rid": "wDhMAJ9xYHE=",
    "Documents": [{
        "id": "c05c4eee-32d4-458a-8ae8-d22dd0f93839",
        "CustomProperty1": "Value 1",
        "CustomProperty2": "Value 2",
        "_rid": "wDhMAJ9xYHECAAAAAAAAAA==",
        "_self": "dbs\/wDhMAA==\/colls\/wDhMAJ9xYHE=\/docs\/wDhMAJ9xYHECAAAAAAAAAA==\/",
        "_etag": "\"00000000-0000-0000-7167-28c107aa01d6\"",
        "_attachments": "attachments\/",
        "_ts": 1597319093
    }],
    "_count": 1
}

The Documents part is my actual "domain" model. How can I easily map this back to a list of my domain model class? I used the same class to write to CosmosDB.

The model looks like this

public class MyModel
{
    [JsonProperty(PropertyName = "id")]
    public Guid Id {get;set;}
    public string CustomProperty1 {get;set;}
    public string CustomProperty1 {get;set;}
}

So how can I query my CosmosDB so that it returns a list of this class?

Upvotes: 0

Views: 3294

Answers (1)

Noah Stahl
Noah Stahl

Reputation: 7553

Here are some samples that I found helpful. The simpler case is to used the typed GetItemQueryIterator<MyModel>, but there is also a stream deserialization example.

Upvotes: 1

Related Questions