Khalil Liraqui
Khalil Liraqui

Reputation: 415

Automapper : UseDestinationValue() and Ignore() methode aren't working

i have two classe User (Destination) and UserViewModel (Source) :

public class User 
    {
        public int Id{ get; set; }
        public string Username{ get; set; }
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public DateTime? DateOfBirth { get; set; }
        public Enums.Sex Sex { get; set; }
        public byte[] ProfilePicture { get; set; }
        public int Score { get; set; }

}

public class ProfileViewModel
    {
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public string PhoneNumber { get; set; }
        public string Email { get; set; }

   }

This is the AutoMapper config :

Mapper.Initialize(cfg =>
{ 
cfg.CreateMap<ProfileViewModel, User>()
.ForMember<int>(u =>u.Id, m => m.Ignore()).ForMember<string>(u=> u.UserName, m => m.Ignore());

});

I'm using it here :

public ActionResult MyProfile(ProfileViewModel m, HttpPostedFileBase profilePicture)
{
     User currentUser = UserRep.GetCurrentUser(User.Identity.GetUserId());
                currentUser = Mapper.Map<User>(m);
...

}

I bring the current user with all the data id, username ... and when i execute the mapping username is null and id = 0 i d'ont understand and i try with ignore() and usedestinationValue()

Upvotes: 1

Views: 1162

Answers (1)

Sylwekqaz
Sylwekqaz

Reputation: 329

When you call Mapper.Map(source) AutoMapper will create a brand new object and fill with data from view model. Its behaves similarly to this code

var temp = new User();
temp.FirstName = source.FirstName;
temp.LastName = source.LastName;
...
return temp;

Look there is no data from orginal user object, and in next step you overwrite reference to orginal object. You should use the overload that takes the existing object as a parameter

public ActionResult MyProfile(ProfileViewModel m, HttpPostedFileBase profilePicture)
{
     User currentUser = UserRep.GetCurrentUser(User.Identity.GetUserId());
     currentUser = Mapper.Map<ProfileViewModel, User>(currentUser, m); // you can skip assign to variable
     ...
}

Mapper.Map(destination,source) behaves similarly to this code

destination.FirstName = source.FirstName;
destination.LastName = source.LastName;
...
return source;

Upvotes: 1

Related Questions