The following illustrates a convenient method of setting up a map between business classes to the Azure Table Storage entities using Automapper.
For this example both Automapper and Azure Table Storage were used:
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
{
Guid Id {
get
;
set
; }
string
Name {
}
And the customer entity is defined as:
CustomerEntity : Microsoft.WindowsAzure.Storage.Table.DataServices.TableServiceEntity
For convenience, I have created a operator methods for converting between Customer and CustomerEntity implicitely (this is added to the CustomerEntity class):
static
implicit
operator
Contracts.Customer(CustomerEntity from)
return
AutoMapper.Mapper.Map<CustomerEntity, Contracts.Customer>(from);
CustomerEntity(Contracts.Customer from)
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.