Search code examples
azuremappingazure-storageazure-table-storage

Azure Table Storage - TableEntity map column with a different name


I am using Azure Table Storage as my data sink for my Semantic Logging Application Block. When I call a log to be written by my custom EventSource, I get columns similar to the ff.:

  • EventId
  • Payload_username
  • Opcode

I can obtain these columns by creating a TableEntity class that matches the column names exactly (except for EventId, for some reason):

public class ReportLogEntity : TableEntity
{
    public string EventId { get; set; }
    public string Payload_username { get; set; }
    public string Opcode { get; set; }
}

However, I would like to store the data in these columns in differently named properties in my TableEntity:

public class ReportLogEntity : TableEntity
{
    public string Id { get; set; } // maps to "EventId"
    public string Username { get; set; } // maps to "Payload_username"
    public string Operation { get; set; } // maps to "Opcode"
}

Is there a mapper/attribute I can make use of to allow myself to have the column name different from the TableEntity property name?


Solution

  • You can override ReadEntity and WriteEntity methods of interface ITableEntity to customize your own property names.

        public class ReportLogEntity : TableEntity
        {
            public string PartitionKey { get; set; }
            public string RowKey { get; set; }
            public string Id { get; set; } // maps to "EventId"
            public string Username { get; set; } // maps to "Payload_username"
            public string Operation { get; set; } // maps to "Opcode"
    
            public override void ReadEntity(IDictionary<string, EntityProperty> properties, OperationContext operationContext)
            {
                this.PartitionKey = properties["PartitionKey"].StringValue;
                this.RowKey = properties["RowKey"].StringValue;
                this.Id = properties["EventId"].StringValue;
                this.Username = properties["Payload_username"].StringValue;
                this.Operation = properties["Opcode"].StringValue;
            }
    
            public override IDictionary<string, EntityProperty> WriteEntity(OperationContext operationContext)
            {
                var properties = new Dictionary<string, EntityProperty>();
                properties.Add("PartitionKey", new EntityProperty(this.PartitionKey));
                properties.Add("RowKey", new EntityProperty(this.RowKey));
                properties.Add("EventId", new EntityProperty(this.Id));
                properties.Add("Payload_username", new EntityProperty(this.Username));
                properties.Add("Opcode", new EntityProperty(this.Operation));
                return properties;
            }
        }