Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Context is not updating loaded entity after being mapped using AutoMapper

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;
like image 759
mohsen dorparasti Avatar asked Nov 23 '12 12:11

mohsen dorparasti


1 Answers

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;
like image 184
Sergey Berezovskiy Avatar answered Oct 22 '22 11:10

Sergey Berezovskiy