3

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

Balaram
  • 43
  • 3
  • 2
    As a side note the `Mapper.CreateMap` static method should be called only once per AppDomain, ideally in Application_Start and not everytime you map. – Darin Dimitrov Nov 21 '11 at 11:09
  • Thanks for the tip Darin, yes, I am storing all my CreateMap codes in a static method of a static class and calling the static method in the Application_Start. Hope that is the best practice. – Balaram Nov 22 '11 at 06:09

1 Answers1

1

I finally decided to change my approach. Having read the below article http://lostechies.com/jimmybogard/2009/09/18/the-case-for-two-way-mapping-in-automapper/ I decided to use Automapper only for entity-to-viewmodel mapping. During the HttpPost event, I am manually assigning the attributes from view model to entity. Sure, it makes my code volumnous, but it does give me control on what gets into the database. Cheers! Bala

Balaram
  • 43
  • 3