Note
Access to this page requires authorization. You can try signing in or changing directories.
Access to this page requires authorization. You can try changing directories.
Summary
The following illustrates a convenient method of setting up a map between business classes to the Azure Table Storage entities using Automapper.
Special Requirements
For this example both Automapper and Azure Table Storage were used:
- Automapper 2.2.1
- Windows Azure Storage 2.0.6.0
Mapping Example
In this example, I am mapping a Customer class to a TableStorageEntity. The TableStorageEntity, named CustomerEntity has the same properties so a map between the two objects is ideal as little logic will need to be written.
The customer business object is defined as:
public class Customer
{
public Guid Id { get; set; }
public string Name { get; set; }
}
And the customer entity is defined as:
public class CustomerEntity : Microsoft.WindowsAzure.Storage.Table.DataServices.TableServiceEntity
{
public Guid Id { get; set; }
public string Name { get; set; }
}
For convenience, I have created a operator methods for converting between Customer and CustomerEntity implicitely (this is added to the CustomerEntity class):
public static implicit operator Contracts.Customer(CustomerEntity from)
{
return AutoMapper.Mapper.Map<CustomerEntity, Contracts.Customer>(from);
}
public static implicit operator CustomerEntity(Contracts.Customer from)
{
return AutoMapper.Mapper.Map<Contracts.Customer, CustomerEntity>(from);
}
To complete the mapping, Automapper needs to have the map created before the implicit conversion is performed. I chose to do this in the constructor of my class performing the TableServiceContext updates:
AutoMapper.Mapper.CreateMap<Customer, ServiceEntities.CustomerEntity>()
.ForMember(m => m.PartitionKey, s => s.UseValue(PARTITIONKEY))
.ForMember(m => m.RowKey, s => s.MapFrom(g => g.Id));
AutoMapper.Mapper.CreateMap<ServiceEntities.CustomerEntity, Customer>();
The following is an example of how the Add could be performed:
protected void Add(Customer customer)
{
var account = CloudStorageAccount.Parse(ConfigurationManager.AppSettings["StorageAccountConnectionString"]);
var tableClient = new CloudTableClient(account.TableEndpoint, account.Credentials);
var context = tableClient.GetTableServiceContext();
context.AddObject("Customer", customer);
context.SaveChanges();
}
For a complete sample, please see the Azure Storage Sample Datalayer Framework.