Kassem
Kassem

Reputation: 8266

Confused About Using AutoMapper

I read a few articles and I've seen the video from MvcConf 1 in which Jimmy Bogard demonstrates the usage of AutoMapper but I'm still confused.

I have a User POCO class which has a bunch of properties. I also have a RegisterViewModel class which contains a sub-set of the User class' properties. Now when a user is registering, she'll be filling the data into the empty RegisterViewModel instance passed to the view. Then this data has to be mapped to the User instance to be added to the database, but there are certain properties on the User which need to be entered as defaults (something like RegistrationDate which should be assigned to DateTime.Now). What would I do in this case?

Moreover, let's say I'm updating a User instance. First I need to get the data from the database and map it to the UpdateUserViewModel class. Then when the user submits the changes, those have to be mapped back to the User instance. In this case, do I need to do two separate Mapper.CreateMap<>() entries in my configuration file or does AutoMapper do that automatically for me?

I guess that's it for now, your help will be highly appreciated! :)

Upvotes: 1

Views: 608

Answers (1)

Darin Dimitrov
Darin Dimitrov

Reputation: 1038720

For the first scenario you could define those missing properties in your mapping:

Mapper
    .CreateMap<RegisterViewModel, User>()
    .ForMember(
        dest => dest.RegistrationDate,
        opt => opt.UseValue(DateTime.Now)
    );

For the second scenario you need two separate mappings because AutoMapper doesn't automatically define bi-directional mappings:

Mapper.CreateMap<UpdateUserViewModel, User>();
Mapper.CreateMap<User, UpdateUserViewModel>();

Upvotes: 5

Related Questions