in my code I'm loading an entity
using its id
, then update its content using AutoMapper
and finally call Context.SaveChanges
. but it's not working ! . but when I set properties manually it takes effect ! what is wrong ?
var entity = Context.MyEntities.Find(id);
entity = Mapper.Map<MyEntity>(viewModel);
Context.SaveChanges;
but this one works :
var entity = Context.MyEntities.Find(id);
entity.SomeProp = viewModel.SomeProp;
Context.SaveChanges;
then update its content using AutoMapper
This is not true - Mapper.Map<MyEntity>(viewModel)
returns new instance of MyEntity
class. It does not update properties of existing instance. You should attach that new instance to context:
var entity = Context.MyEntities.Find(id); // this line is useless
entity = Mapper.Map<MyEntity>(viewModel);
Context.MyEntities.Attach(entity);
Context.SaveChanges;
Also retrieving entity from context does not makes sense when you are creating new one. You are reusing same variable for holding references to different objects, and that is confusing. What really happens could be described this way:
var entityFromDb = Context.MyEntities.Find(id);
var competelyNewEntity = Mapper.Map<MyEntity>(viewModel);
Context.MyEntities.Attach(competelyNewEntity);
Context.SaveChanges;
In your second option you are updating properties of entity, which exists in context, you don't need to attach it.
BTW there is third option (and best) - use another mapping method, which updates destination entity instead:
var entity = Context.MyEntities.Find(id);
Mapper.Map(viewModel, entity); // use this method for mapping
Context.SaveChanges;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With