Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
using Automapper vs Custom Object Mapper(with reflection) for data transformation of objects
public class BaseModel
{
public Guid Id { get; set; }
public DateTime CreateDate { get; set; }
public bool IsActive { get; set; }
public string LastUpdatingUserName { get; set; }
public DateTime LastUpdatingDate { get; set; }
}
public class BaseViewModel
{
public Guid Id { get; set; }
}
public class Product
: BaseModel
{
public string Name { get; set; }
public decimal Price { get; set; }
public string Description { get; set; }
public int Stock { get; set; }
}
public class ProductViewModel
: BaseViewModel
{
public string Name { get; set; }
public decimal Price { get; set; }
public string Description { get; set; }
public int Stock { get; set; }
}
//Helper class for object mapping
public static class ObjectMap
{
public static TViewModel MapViewModelToModel<TViewModel>(this BaseModel model, TViewModel viewModel)
where TViewModel : class
{
if (model == null || viewModel == null)
return null;
Type ModelObjectType = model.GetType();
PropertyInfo[] modelPropList = ModelObjectType.GetProperties();
Type ViewModelType = viewModel.GetType();
PropertyInfo[] viewModelPropList = ViewModelType.GetProperties();
foreach (PropertyInfo modelPropInfo in modelPropList)
{
foreach (PropertyInfo viewModelPropInfo in viewModelPropList)
{
if (modelPropInfo.Name == viewModelPropInfo.Name &&
!modelPropInfo.GetGetMethod().IsVirtual && !viewModelPropInfo.GetGetMethod().IsVirtual)
{
viewModelPropInfo.SetValue(viewModel, modelPropInfo.GetValue(model, null), null);
break;
}
}
}
return viewModel;
}
}
// let's use our codes :D
class Program
{
static void Main(string[] args)
{
Product product = new Product
{
Id = Guid.NewGuid(),
CreateDate = DateTime.Now,
LastUpdatingDate = DateTime.Now,
Description = "Description",
IsActive = false,
LastUpdatingUserName = "YUNUSEMR",
Name = "IPHONE 5",
Price = 2000,
Stock = 13
};
#region data transformation with AutoMapper
Stopwatch sw = new Stopwatch();
sw.Start();
// can define in bootstrapper class
Mapper.CreateMap<Product, ProductViewModel>();
ProductViewModel productViewModel = Mapper.Map<Product, ProductViewModel>(product);
sw.Stop();
Console.WriteLine("Elapsed time 1 :>" + sw.Elapsed.TotalMilliseconds);
Console.WriteLine("with AutoMapper " + productViewModel.Description + " - " + productViewModel.Name);
#endregion
#region data transformation with Reflection
Stopwatch sw1 = new Stopwatch();
sw1.Start();
ProductViewModel productViewModel1 = new ProductViewModel();
ObjectMap.MapViewModelToModel<ProductViewModel>(product, productViewModel1);
Console.WriteLine("Elapsed time 2 :>" + sw1.Elapsed.TotalMilliseconds);
Console.WriteLine("with Reflection " + productViewModel1.Description + " - " + productViewModel1.Name);
sw.Stop();
#endregion
Console.ReadLine();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment