In WebAPI 2 using Json.Net a SQL Server Timestamp serializes but does not deserialize

Viewed 1732

A SQL Server Timestamp becomes a byte[] in a POCO object. The object gets serialized and the timestamp becomes a base 64 string.

An example is 'AAAAAAA2QDE='

When the object is posted back to the server, during Model Validation you get:

The value 'AAAAAAA2QDE=' is not valid for Byte.

I am using this value to check the state of the record to compare to the current record in SQL to see if someone else has updated it since this user has retrieved it (pretty normal).

But the string is not deserializing back to a byte array, it appears that it is trying to put it into a single byte.

This should be a very common issue. Any ideas?

1 Answers

We can map the SQL Column (via ORM like NHibernate...) or directly with ADO.NET to property of type byte[], but make this property protected/internal to the server. Instead this, we can have another string property doing conversion as needed:

protected virtual byte[] Timestamp { get; set; }
public virtual string Version
{
    get { return Timestamp.IsEmpty() ? null : Convert.ToBase64String(Timestamp); }
    set { Timestamp = value.IsEmpty() ? null : Convert.FromBase64String(value); }
}

The Timestamp is for internal processing, representing the real bytes, the Version is for a Client ... is well de/serialized.

An example with NHibernate here

Related