Home > Enterprise >  When I use Automapper for my model. model's Id is changing
When I use Automapper for my model. model's Id is changing

Time:09-05

This is my first question so I am very nervous :) You can see the question below :

This is my mapping profile

CreateMap<UpdateUserVM, AppUser>().ForAllMembers(a => a.UseDestinationValue());

My Viewmodel has not Id's property. In the same time I am using IdentityFramework for my project.

Here are the my method. When I use this method my models id is changing. If you can help me I will be very happy :) Thanks

public async Task<object> UpdateUser(UpdateUserVM updateUserVM, string id)
{
    AppUser user = await userManager.FindByIdAsync(id);
    user = mapper.Map<AppUser>(updateUserVM);
    var result = await userManager.UpdateAsync(user);
    string msg = string.Empty;
    if (!result.Succeeded)
    {
        foreach (var error in result.Errors)
        {
            msg  = $"{error.Code} - {error.Description}\n";
        }
        return msg;
    }
    return true;
}

CodePudding user response:

There is a different Map method overload that is specifically used to update properties on existing destination object:

mapper.Map(updateUserVM, user);

So, in your sample code it would be:

public async Task<object> UpdateUser(UpdateUserVM updateUserVM, string id)
{
    AppUser user = await userManager.FindByIdAsync(id);
    mapper.Map(updateUserVM, user); // use different `Map` overload
    var result = await userManager.UpdateAsync(user);
    string msg = string.Empty;
    if (!result.Succeeded)
    {
        foreach (var error in result.Errors)
        {
            msg  = $"{error.Code} - {error.Description}\n";
        }
        return msg;
    }
    return true;
}
  • Related