Tom
Tom

Reputation: 984

Cosmodb, why is this update not working?

I am trying to query orders and update them. I have been able to isolate my problem in a unit test:

    [Fact(DisplayName = "OrderDocumentRepositoryFixture.Can_UpdateAsync")]
public async void Can_UpdateByQueryableAsync()
{
    var order1 = JsonConvert.DeserializeObject<Order>(Order_V20170405_133926_9934934.JSON);
    var orderId1 = "Test_1";
    order1.Id = orderId1;
    await sut.CreateAsync(order1);


    foreach (var order in sut.CreateQuery())
    {
    order.Version = "myversion";
        await sut.UpdateAsync(order);
        var ordersFromDb = sut.GetByIdAsync(orderId1).Result;
        Assert.Equal("myversion", ordersFromDb.Version);
    }
}

where :

public IQueryable<T> CreateQuery()
{
    return _client.CreateDocumentQuery<T>(UriFactory.CreateDocumentCollectionUri(_databaseId, CollectionId));
}

With this code, orders are not updated.

If I replace the CreateQuery() by what follows, it does work:

[Fact(DisplayName = "OrderDocumentRepositoryFixture.Can_UpdateAsync")]
public async void Can_UpdateByQueryableAsync()
{
    var order1 = JsonConvert.DeserializeObject<Order>(Order_V20170405_133926_9934934.JSON);
    var orderId1 = "Test_1";
    order1.Id = orderId1;
    await sut.CreateAsync(order1);


        var order = sut.GetByIdAsync(orderId1).Result;

    order.Version = "myversion";
        await sut.UpdateAsync(order);
        var ordersFromDb = sut.GetByIdAsync(orderId1).Result;
        Assert.Equal("myversion", ordersFromDb.Version);

}

where

public async Task<T> GetByIdAsync(string id)
{
    try
    {
        var documentUri = UriFactory.CreateDocumentUri(_databaseId, CollectionId, id);
        var document = (T) await ((DocumentClient) _client).ReadDocumentAsync<T>(documentUri);

        return document;
    }
    catch (DocumentClientException e)
    {
        if (e.StatusCode == HttpStatusCode.NotFound) return null;
        throw;
    }
}

I've been trying to understand why this doesn't work. Obviously i could always do a GetByIdAsync before updating, but that seems overkill?

What can't I see?

Thanks!

Upvotes: 1

Views: 272

Answers (1)

David Makogon
David Makogon

Reputation: 71121

You create your query, but you never execute it (CreateDocumentQuery just sets up the query). Try altering your call to something like:

foreach (var order in sut.CreateQuery().ToList())
{
   //
}

Also note: if you are always querying for a single document, and you know the id, then ReadDocumentAsync() (your alternate code path) will be much more effecient, RU-wise.

Upvotes: 0

Related Questions