I'm using Automapper in my MVC/EF Code First project. While mapping a ViewModel into View, I am using a customer converter class inherited from TypeConverter. I am setting up the mapping using the below code:
Mapper.CreateMap<CustomerViewModel, Customer>().ConvertUsing<CustomerConverter>();
where CustomerConverter is my TypeConverter class.
This works fine while creating a new Customer entity and saving to db
Customer customer = Mapper.Map<CustomerViewModel, Customer>(viewModel);
dbEntities.Customer.Add(customer);
dbEntities.SaveChanges();
But while editing an existing customer, I found that the changes to customer object are not getting saved.
The code I use to handle existing customer updates is as follows
var customer = dbEntities.Customer.Single(a => a.CustomerId == viewModel.CustomerId.Value);
Mapper.CreateMap<ExistingCustomerViewModel, Customer>().ForMember(dest => dest.CustomerId, opt => opt.Ignore()).ConvertUsing<ExistingCustomerConverter>();
Mapper.Map<ExistingCustomerViewModel, Customer>(viewModel, customer);
dbEntities.Entry(customer).State = EntityState.Modified;
dbEntities.SaveChanges();
I use a different viewmodel and customer converter to handle existing customer since I display only limited fields for updating existing customers.
The problem is, with the above code, the customer record is not updated. I find that, if I remove the custom conversion, the customer record is updated.
i.e.,
Mapper.CreateMap<ExistingCustomerViewModel, Customer>().ForMember(dest => dest.CustomerId, opt => opt.Ignore());
works correctly, but I lose my ability to apply custom mapping.
Am I missing something? Thanks for helping!
Thanks! Bala