1

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()

Khalil Liraqui
  • 385
  • 1
  • 5
  • 21

1 Answers1

1

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;
Sylwekqaz
  • 329
  • 2
  • 9
  • Perfeeect , works like a charm but i saw many answars to other question that wont work check this for example : https://stackoverflow.com/questions/17147099/automapper-can-it-map-over-only-existing-properties-in-source-and-destination – Khalil Liraqui Oct 29 '17 at 23:37