开发者

Two way conversion using AutoMapper

I have my viewmodel classes and also my wcf service classes (separate project). I need to convert the viewmodel classes to wcf classes and also the other way around. Currently I am using the following method:

public static class ExtensionMethods
{
    public static object To<T>(this object source)
    {
        // create the map
        Mapper.CreateMap(source.GetType(), typeof (T)); 

        // if the source is a list
        if(source is IEnumerable)
        {
            return Mapper.Map(source, source.GetType(), typeof (List<T>)); 
        }

        // return the mapping 
        return (T) Mapper.Map(source, source.GetType(), typeof (T)); 
    }

}

// converting the wcf class to viewmodel
var orders = (List<OrderStatusViewModel>) _orderStatusServiceClient.GetRecentOrders().To<OrderStatusViewModel>();
// converting the viewmodel to the wcf class 
var order = (Order) orderStatusViewModel.To<Order>();  

Is this the best way to do this? Keep in mind I have to perform this in both the directions i开发者_JAVA百科.e viewmodel => wcf classes and wcf classes => viewmodel.


One thing to be careful of is redefining your maps over and over again. I've had code blow up from this.

Since your method is not tied to any specific types, I would recommend removing the CreateMap call and changing the Map calls to DynamicMap.

Also, if your generic parameter type is IEnumerable when your input is, then your if would be unnecessary with DynamicMap

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜