c# - Force Automapper to use ConstructUsing even if nested entity is already created -
please suppose domain
public class customer : entity { public int id { get; set; } public string name { get; set; } public image photo { get; set;} public int photoid { get; set; } } public class image : entity { public int id { get; set; } public byte[] content { get; set; } }
now suppose models
public class customermodel : entitymodel { public int id { get; set; } public string name { get; set; } public imagemodel photo { get; set;} public int photoid { get; set; } } public class imagemodel : entitymodel { public int id { get; set; } public byte[] content { get; set; } }
suppose have customer on database, attached dbcontext:
customer = { id : 1, name : "alexandre", photoid: 13, photo : { id: 13, content: abc } }
and model (posted user browser):
customermodel = { id : 1, name : "alexandre", photoid: 0, photo : { id: 0, content: xyz } }
so, how can see, user creates new photo (id == 0) not still saved database, , replace on entity.
the problem : if call
mapper.map(customermodel, customer)
automapper map customermodel.photo customer.photo, instead of creates new one, , entity framework raise exception because can't change pk of image object.
also, can't
customer.photo = null
before map objects because mapping generics, , base classes not knows structure of these objects. big application many entities, don't want execute code every nested property on every entity.
so need more genereic...
what want: automapper must knows these photos not same (by comparing ids) , creates new 1 instead of replace same.
is possible?
this map forces creation of new image
object accordingly id
comparison:
mapper.createmap<customermodel, customer>() .beforemap((src, dest) => dest.photo = dest.photo.id != src.photo.id ? new image() : dest.photo);
edit: more generic approach:
mapper.createmap<customermodel, customer>().beforemap(action); mapper.createmap<foomodel, foo>().beforemap(action); private static void action(entitymodel src, entity dest) { //get actual object properties via reflection, compare, re-create... }
Comments
Post a Comment