user1567095
user1567095

Reputation: 480

Avoid primary key duplicates in Windows Azure

In Windows Azure table storage, there is no 'type' that allows an auto incrementing ID. I thought I could use 'IsIdentity' but the checkbox is greyed out (this should give me auto incrementing, right?).

Can anybody advise me on how I can get an auto incrementing field or a workaround please?

Thanks!

Upvotes: 3

Views: 2626

Answers (1)

Mark Rendle
Mark Rendle

Reputation: 9414

Unless, for some reason, you actually need monotonically-increasing numeric keys, then using DateTime.UtcNow.Ticks.ToString() is the usual approach. (Because the PartitionKey value on Table Storage is a string, you need to convert it.)

The advantage to this approach is that Table Storage rows are automatically ordered by the PartitionKey (and then by the RowKey), so you'll get the rows back in the order they were inserted, just like an IDENTITY column in SQL Server.

If you want the records returned most-recent-first, then use (long.MaxValue - DateTime.UtcNow.Ticks).ToString() instead.

Note that the first method will give an 18-digit number for the next 1158 years. If you want to avoid the Y3160 bug, consider padding the value with a leading zero (DateTime.UtcNow.Ticks.ToString("0000000000000000000")).

The second method will give a 19-digit number for a very long time indeed, way past DateTime.MaxValue, so you're probably OK there.

Also bear in mind that with load-balancing and suchlike, there is a very small possibility that you'll get duplicates if two servers create a record at the exact same time, so you should have retry semantics that increment the key value by one.

Upvotes: 7

Related Questions