2

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;
}
ˈvɔlə
  • 9,204
  • 10
  • 63
  • 89
Arda Şen
  • 47
  • 4
  • 1
    Does this answer your question? [In .Net Core 6 Api, how to map only the values that exist in the DTO uisng AutoMapper 11?](https://stackoverflow.com/questions/73429751/in-net-core-6-api-how-to-map-only-the-values-that-exist-in-the-dto-uisng-autom) – Progman Sep 04 '22 at 15:47
  • @Progman not the best answer in your link. No need to manually update properties when AutoMapper can do that for us. And... it's slightly different question. Here we don't have `Id` on view-model. – Nenad Sep 04 '22 at 15:55
  • 1
    @Nenad There are other answers in that question, including https://stackoverflow.com/a/73432823/286934 where I explain to use the `Map()` overload with the second parameter. – Progman Sep 04 '22 at 15:57
  • @Progman It's different question. And the best answer would be to set mapping the `Id` on destination to "ignore". Writing `Id = id` manually to both source and destination is not necessary. Perhaps I should answer that question correctly (from AutoMapper perspective) as well. – Nenad Sep 04 '22 at 16:01

1 Answers1

2

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;
}
Nenad
  • 24,809
  • 11
  • 75
  • 93