0

I have the following:

    public async Task<bool> Update(CoinEntity coinEntity)
    {

        var found = await context.Coins.FindAsync(coinEntity.CoinId);
        if(found==null)
        {
            throw new CoinNotFoundException(coinEntity.CoinId);
        }

        Mapper.Initialize(cfg => cfg.CreateMap<CoinEntity, CoinEntity>());
        found = Mapper.Map<CoinEntity>(coinEntity);
        await context.SaveChangesAsync();

        return true;


    }

This works in sense that the found has all properties from the one passed in, however because the .Map creates a new instance, I assume. This is no longer being tracked by EFCore and SaveChanges has nothing changed.

Is there a way for automapper to actually update an actual object instead of creating a new instance?

I simply want my found object to still be tracked by EF after automapper does its mapping.

I am trying to avoid having to copy field by field, and using .Attach of EF is not an option because it doesnt work since I need to replace child table records (deleting some, adding some)

Zoinky
  • 4,083
  • 11
  • 40
  • 78
  • 4
    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) – A Friend Dec 18 '18 at 14:44
  • You are missusing automapper here. You can call the static Initialize only once, but yo do this every time your method is called. Move initialize somewhere to the beginning of the code flow. If this is asp.net core, you can use automapper's scoped service instead of the static access, which is more suitable for this scenario. – ZorgoZ Dec 18 '18 at 14:49
  • yep i am aware of that one, that was just done to make sure it works before i move it. Thank you for pointing that out though – Zoinky Dec 18 '18 at 14:50
  • @AFriend this is what I am looking fore, thanks, answered my q – Zoinky Dec 18 '18 at 14:51

0 Answers0