r3plica
r3plica

Reputation: 13387

c# Cosmos Db check if file exists before creating

I have this method:

public async Task SaveAsync(IEnumerable<JObject> models)
{
    foreach (var document in models)
    {
        var collectionLink = UriFactory.CreateDocumentCollectionUri(_databaseName, _collectionName);
        await _client.CreateDocumentAsync(collectionLink, document);
    }
}

Which is fine when creating multiple documents at once, but if I have a document that has the same id as one already in the database I get an error:

Entity with the specified id already exists in the system.

Because the document is actually different I am not sure I can check to see if it exists already.

Is there a way of replacing the existing entity with the new one?

Upvotes: 2

Views: 1825

Answers (1)

Panagiotis Kanavos
Panagiotis Kanavos

Reputation: 131591

You can use DocumentClient.UpsertDocumentAsync instead of CreateDocumentAsync to create a new document or update the existing one, eg:

await _client.UpsertDocumentAsync(collectionLink, document);

Upvotes: 2

Related Questions