Note
Access to this page requires authorization. You can try signing in or changing directories.
Access to this page requires authorization. You can try changing directories.
Question
Friday, May 17, 2013 5:17 AM | 1 vote
My entity is like:
MytEntity
{
public long Id { get; set; }
}
I want the Id whose type must be long auto-incrementing and unique.
I use below method:
- select the entity
- increase Id
- save changes
Here is the code:
var context_ = storageTable.GetDataServiceContext();
var queryObj = context_.CreateQuery<MytEntity>(TableName);
var results = from g in queryObj
where g.Id == _Id
select g;
MytEntity Entity = results.FirstOrDefault< MytEntity >();
Entity.Id++;
context_.UpdateObject(Entity);
context_.SaveChangesWithRetries();
But when the code is running in threads/multi instances, it may be incorrect.
So I use lock mechanism. But the efficiency of lock mechanism is not high especially in multi instances.
Anyone has good solution for auto-incrementing and unique id? Thanks.
All replies (4)
Friday, May 17, 2013 6:45 AM âś…Answered
Hi,
As I know the lock way is the best way for doing auto-incrementing. You may try with other workaround from the following links:
http://stackoverflow.com/questions/1870327/auto-increment-on-azure-table-storage
http://stackoverflow.com/questions/12334012/avoid-primary-key-duplicates-in-windows-azure
http://stackoverflow.com/questions/13398097/windows-azure-table-storage-int-field-increment
Thanks,
QinDian Tang
MSDN Community Support | Feedback to us
Develop and promote your apps in Windows Store
Please remember to mark the replies as answers if they help and unmark them if they provide no help.
Thursday, May 30, 2013 1:52 AM
Thanks reply.
Since the lock way is the best way, can you please tell me how to implement 'Lock' in Azure multi Instances? Thanks.
Thursday, May 30, 2013 2:56 AM
Hi,
After I think about it again. Locking is not the best way. Actually in table storage, we don't have built-in auto-incrementing as sql table does. Incrementing or not is not the key point here. The point is to give a unique identity key for each entity. The easy way is to input some unique value into RowKey such as current datetime appended with instance id, if you have multiple instance.
Thanks,
QinDian Tang
MSDN Community Support | Feedback to us
Develop and promote your apps in Windows Store
Please remember to mark the replies as answers if they help and unmark them if they provide no help.
Thursday, May 30, 2013 3:16 AM
Thanks.
I was going to use RowKey to implement Lock way:
Entity.RowKey="Lock";
Context.AddObject(TableName, Entity);
try
{
Context.SaveChanges();
}
catch(exception)
{
}
If I can save this entity, I treat it as lock succeed.
When unlock, I delete this entity.
But lock way is not good for parallel arithmetic, as you say. So I will use your method:
input some unique value into RowKey such as current datetime.