Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
public virtual async Task<T> SaveOrUpdate(T data)
{
var document = await GetById(data.Id);
if (document == null)
{
await Insert(data);
}
else
{
data.ModificationDate = DateTime.UtcNow;
var ac = new AccessCondition { Condition = data.ETag, Type = AccessConditionType.IfMatch };
try
{
var output = await Client.ReplaceDocumentAsync(
UriFactory.CreateDocumentUri(DatabaseId, CollectionId, document.Id),
data, new RequestOptions
{
AccessCondition = ac
});
document.ETag = output.Resource.ETag;
data.ETag = output.Resource.ETag;
}
catch (DocumentClientException ex)
{
if (ex.StatusCode == HttpStatusCode.PreconditionFailed)
{
throw new OptimisticConcurrencyException(
$"Impossible to replace document '{data.Id}' from collection '{CollectionId}'. Precondition failed.", ex);
}
}
}
return document;
}
public async Task<T> SaveOrUpdateOptimistically(string id, Action<T> modifier)
{
var doc = await GetById(id);
try
{
modifier(doc);
await SaveOrUpdate(doc);
return doc;
}
catch (OptimisticConcurrencyException)
{
return await SaveOrUpdateOptimistically(id, modifier);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.