Using a free AutoMapper Component to Mapping Classes
Scott Mitchell in this month issue of MSDN Magazine has a cool post that has introduced a small tools about Data Mapping.
Usually in enterprise applications developers don't use data access objects directly in other layers such as business layer.
In this situations they map data access objects to Data Transfer Objects (DTO). DTO objects often have the same properties (or less/more) with data access objects.
For better understanding let take an example.
Assume we have Order and OrderDatail Tables in database and we want to use "LINQ to SQL" to retrieve a given order. we have an Order class that generated in LINQ to SQL File and an OrderDTO Class that we created it.
public class Order
{
public int OrderID { get; set; }
public string ShipName { get; set; }
public IEnumerable<OrderDetail> OrderDetails { get; set; }
//Secure Property
public string SecretProperty { get; set; }
.
.
.
}
public class OrderDTO
{
public int OrderID { get; set; }
public string ShipName { get; set; }
public List<OrderDetail> OrderDetails { get; set; }
// in example, here we have not secret property for security reasons
}
Now we should write a function to map order object to orderDTO object.
public OrderDTO MapToDTO(Order order)
{
OrderDTO orderDTO = new OrderDTO();
orderDTO.OrderID = order.OrderID;
orderDTO.ShipName = order.ShipName;
orderDTO.OrderDetails = order.OrderDetails.ToList();
return orderDTO;
}
in our case because classes have a few property, this work is easy but in real world cases, this work is tedious and time consuming. specially when there is collections and other complex data types.
AutoMapper is a free & open source component that make the mapping so easy. here we write above function with AutoMapper library.
public OrderDTO MapToDTO(Order order)
{
Mapper.CreateMap<Order, OrderDTO>();
Mapper.CreateMap<OrderDetail, OrderDetailDTO>();
OrderDTO orderDTO = Mapper.Map<Order, OrderDTO>(order);
return orderDTO;
}
Just that! whit this three lines code, we made all works. CreateMap Method is responsible for mapping structure between data access class and DTO class.
With calling Map Method, All works done and orderDTO is filled with related data.
In the following code snippet we used MapToDTO function in a data access method.
public OrderDTO GetOrder(int orderID)
{
OrderDataContext context = new OrderDataContext("Connection String");
DataLoadOptions loadOptions=new DataLoadOptions();
loadOptions.LoadWith<Order>(m=>m.OrderDetails);
context.LoadOptions = loadOptions;
Order order = context.Orders.Where(m => m.OrderID == orderID).SingleOrDefault();
OrderDTO orderDTO = MapToDTO(order);
return orderDTO;
}
Now you can use orderDTO object in any where such as WCF services and else.
Use it and enjoy.