Bad Request when inserting data to Azure Table Storage

Recently I faced a bit irritating problem when working with Azure Table Storage - I could not insert

Recently I faced a bit irritating problem when working with Azure Table Storage - I could not insert an entity because of the following error:

The remote server returned an error: (400) Bad Request.

Yes, this is incredibly helpful message I got there. Let's assume we have following entity schema:

/
private class Entity : TableEntity
{
	public DateTime SomeDateTime { get; set; }
}

So far so good - it couldn't be easier. Now let's use following code:

/
var storageAccount = CloudStorageAccount.Parse("UseDevelopmentStorage=true");
var tableClient = storageAccount.CreateCloudTableClient();
var table = tableClient.GetTableReference("foo");

table.CreateIfNotExists();
table.Execute(
	TableOperation.Insert(new Entity
	{
		PartitionKey = "bar", 
		RowKey = Guid.NewGuid().ToString()
	}));

In the above snippet we are creating a table and immediately inserting an entity. Notice that I didn't set SomeDateTime value - it will be default one. When you execute it, you will get a nice Bad Request error. What did actually happen?

Storage Table types

Sometimes it's easy to forget that Table Storage supports only a subset of data types defined in OData Protocol Specification(because it's possible to query it with OData statements). If you take a look at documentation here, you'll notice following definition:

Edm.DateTime DateTime A 64-bit value expressed as Coordinated Universal Time (UTC). The supported DateTime range begins from 12:00 midnight, January 1, 1601 A.D. (C.E.), UTC. The range ends at December 31, 9999.

So basically the minimum what can be stored in Table Storage is 01.01.1601. Of course DateTime.MinValue is far from correct...

Storage Emulator

What is even more important, there's a difference between handling dates between Table Storage and emulator. Let's add the same rows to both instances:

/
table.Execute(
	TableOperation.Insert(new Entity
	{
		PartitionKey = "bar", 
		RowKey = Guid.NewGuid().ToString(),
		SomeDateTime = new DateTime(1601, 1, 2)
	}));

Here you can find what I got:

  • 0001-01-01T00:00:00.000Z for Emulator
  • 1601-01-01T23:00:00.000Z for Table Storage

Although documentation says:

Date properties in the Table service in the storage emulator support only the range supported by SQL Server 2005 (they are required to be later than January 1, 1753). All dates before January 1, 1753 are changed to this value. The precision of dates is limited to the precision of SQL Server 2005, meaning that dates are precise to 1/300th of a second.

I see that it rather inserts DateTime.MinValue instead what is really confusing.

 

 

Add comment