5

I want to update an existing entity object from another model. But each time I got a new object (Having the mapped properties and default values for other properties.) Instead, I want a partially updated destination object.

AutoMapper.Mapper.Initialize(cfg => cfg.CreateMap<Customer, MYPOCO>().ReverseMap());


public void UpdateEntity(Customer customerSrc)
{
    MYPOCO pocoDesc= dbContext.DD_POCO.SingleOrDefault(m => m.Id == 123);
    pocoDesc = AutoMapper.Mapper.Map<Customer, MYPOCO>(customerSrc, pocoDesc);

  // Here "pocoDesc" is a new object, I got only "customerSrc" data and lost all other existing properties values.
}

Automapper: 6.2.2(version)

Tried Automapper: Update property values without creating a new object

Any Idea?

Linoy
  • 1,363
  • 1
  • 14
  • 29
  • This appears to be a duplicate of: https://stackoverflow.com/questions/2374689/automapper-update-property-values-without-creating-a-new-object?utm_medium=organic&utm_source=google_rich_qa&utm_campaign=google_rich_qa – Maess May 25 '18 at 15:37
  • Possible duplicate of [Automapper: Update property values without creating a new object](https://stackoverflow.com/questions/2374689/automapper-update-property-values-without-creating-a-new-object) – Maess May 25 '18 at 15:38
  • You are using the correct `Map` overload, so your `pocoDesc` should be the same instance obtained by the `SingleOrDefault` call. Are you sure `SingleOrDefault` doesn't return `null`? How aboiut changing it to `Single`? – Ivan Stoev May 25 '18 at 15:41
  • SingleOrDefault returns correct data, not null – Linoy May 25 '18 at 15:55
  • @IvanStoev Tried with Single but not getting updated object – Linoy May 25 '18 at 16:04
  • It was just to prove the destination entity is not `null`. Honestly it's hard to believe the above code does not update the existing object. I'm doing this all the time and it works as expected, do you have a full repro? Or in other words, is to posted code complete or there is something not shown there? – Ivan Stoev May 25 '18 at 16:11
  • It's probably not a new object. Have you tried assigning it to a different variable and checking for reference equality? – aaron May 25 '18 at 17:26

1 Answers1

5

if it still issue, try the following :

public void UpdateEntity(Customer customerSrc)
{
    MYPOCO pocoDesc= dbContext.DD_POCO.SingleOrDefault(m => m.Id == 123);
    AutoMapper.Mapper.Map<Customer, MYPOCO>(customerSrc, pocoDesc);
    dbContext.DD_POCO.Update(pocoDesc);
    dbContext.Save();
}
Pepe Alvarez
  • 1,218
  • 1
  • 9
  • 15
Mohammed
  • 61
  • 2
  • 4