Azure Table Storage sdk 1.6 Upsert not inserting
-
23-03-2021 - |
質問
I'm trying to use the new upsert feature of asure sdk 1.6 (against the storage emulator).
But I only managed to get the update working. When I try to upsert whit a new rowkey I get resource not found
exception.
var context = new TableServiceContext(_cloudStorageAccount.TableEndpoint.ToString(), _cloudStorageAccount.Credentials)
{
MergeOption = MergeOption.NoTracking,
ResolveType = (unused) => typeof(SmartTableServiceEntity)
};
context.AttachTo(tableName, smartEntity, "*");
context.UpdateObject(smartEntity);
context.SaveChangesWithRetries(SaveChangesOptions.ReplaceOnUpdate);
If I put AddObject
it does the insert but not the update.
I was thinking being able to do both in one action thanks to the new sdk.
解決 2
I came up this a solution that seems to works on devstorage and on real storage
var context = CreateNewContext();
context.IgnoreResourceNotFoundException = true;
if (context.StorageCredentials.AccountName == "devstoreaccount1")
{
var entityCheck = context.CreateQuery<SmartTableServiceEntity>(tableName)
.Where(e => e.PartitionKey == partitionKey && e.RowKey == rowKey).FirstOrDefault();
if (entityCheck == null) {
context.AddObject(tableName, smartEntity);
}
else {
context.Detach(entityCheck);
context.AttachTo(tableName, smartEntity, "*");
context.UpdateObject(smartEntity);
}
}
else
{
context.AttachTo(tableName, smartEntity, null);
context.UpdateObject(smartEntity);
}
context.SaveChangesWithRetries(SaveChangesOptions.ReplaceOnUpdate);
does someone has a better solution? notice the difference bettween "*" and null is it ok?
thank you by advance
他のヒント
it will only work against real Azure storage. Development storage does not support Upsert operation. Also you must set the IgnoreResourceNotFoundException property of the tableServiceContext to true.
When using the real Azure accounts, as well as setting the IgnoreResourceNotFoundException to true, it is also important to pass null for the eTag parameter, or use the overload that does not accept the eTag value. Otherwise you will get ResourceNotFound exceptions.