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;
This is not true –
Mapper.Map<MyEntity>(viewModel)returns new instance ofMyEntityclass. It does not update properties of existing instance. You should attach that new instance to context: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:
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: