August 14, 2011

Removing the TableServiceEntity dependency

I struggled to find a reference on how you can use Azure Table Storage without requiring that your classes inherit from TableServiceEntity.

Why wouldn’t we want to inherit from this class? For a start, it’s in the Microsoft.WindowsAzure.StorageClient assembly. We’re developing loosely coupled applications, and this would be an unnecessary (and unwanted) dependency.

The solution is surprisingly simple, create your own base class with the same properties and decorate it with a DataServiceEntityAttribute (you’ll need a reference to System.Data.Services.Client.dll). I imagine the storage client is using reflection to access these properties, hence why the property names need to match.

public abstract class TableEntity
    protected TableEntity()

    protected TableEntity(string partitionKey, string rowKey)
        this.PartitionKey = partitionKey;
        this.RowKey = rowKey;

    public virtual string PartitionKey { get; set; }
    public virtual string RowKey { get; set; }
    public DateTime Timestamp { get; set; }

However, this base class (and indeed the default TableServiceEntity) has a number of shortcomings. Fabio addresses many of these here and provides a much better base class implementation. Definitely worth a look.

© 2021 Ben Foster