public static void Main()
Mapper.Initialize(config => {
config.CreateMap<Customer, CustomerIndexViewModel>();
config.CreateMap<CustomerBaseViewModel, Customer>()
.ForMember(x => x.Id, opts => opts.Ignore())
.ForMember(x => x.Name, opts => opts.MapFrom((src => src.Name.ToUpper())));
config.CreateMap<CustomerUpdateViewModel, Customer>();
config.ForAllMaps((typeMap, expression) => {
if (typeMap.SourceType.GetInterfaces().Contains(typeof(IBaseAuditable)) && typeMap.DestinationType.GetInterfaces().Contains(typeof(IEntity)))
throw new AutoMapperMappingException("Source type "+typeMap.SourceType.Name+
" and dest type "+typeMap.DestinationType.Name+
" implements IAuditable. Ensure you are not trying to map an auditable VM to an IEntity");
if (typeMap.DestinationType.GetInterfaces().Contains(typeof(IEntity)))
.ForMember("UpdatedBy", opts => opts.Ignore());
Mapper.AssertConfigurationIsValid();
var customer = new Customer();
customer.UpdatedBy = "John";
var CustomerIndexViewModel = Mapper.Map<CustomerIndexViewModel>(customer);
Console.WriteLine("Mapped Entity to Index VM:");
Console.WriteLine("\t" + CustomerIndexViewModel.Id);
Console.WriteLine("\t" + CustomerIndexViewModel.Name);
Console.WriteLine("\t" + CustomerIndexViewModel.UpdatedBy);
var updateVm = new CustomerUpdateViewModel();
var updatedCustomer = Mapper.Map<Customer>(updateVm);
Console.WriteLine("Mapped Update VM to Entity:");
Console.WriteLine("\t" + updatedCustomer.Id);
Console.WriteLine("\t" + updatedCustomer.Name);
Console.WriteLine("\t" + updatedCustomer.UpdatedBy);
var createVm = new CustomerBaseViewModel();
var createdCustomer = Mapper.Map<Customer>(createVm);
Console.WriteLine("Mapped Create VM to Entity:");
Console.WriteLine("\t" + createdCustomer.Id);
Console.WriteLine("\t" + createdCustomer.Name);
Console.WriteLine("\t" + createdCustomer.UpdatedBy);
public interface IBaseAuditable
string UpdatedBy { get; set; }
public class Customer : IEntity, IBaseAuditable
public int Id { get; set; }
public string UpdatedBy { get; set; }
public string Name { get; set; }
public class CustomerBaseViewModel
public string Name { get; set; }
public class CustomerIndexViewModel : CustomerBaseViewModel, IBaseAuditable
public int Id { get; set; }
public string UpdatedBy { get; set; }
public class CustomerUpdateViewModel : CustomerBaseViewModel
public int Id { get; set; }