model - AutoMapper, how to keep references between mapped objects? -
i using automapper convert ui model pocos later serialize xml using datacontractserializer in order preserve references between them.
the problem comes that, when mapping, the references between entities lost.
the ui classes reference each other, mapping process makes new instances every reference, original relations broken :(
let me explain:
i have 2 entities of type person
person { list<house> ownedhouses }
and these 2 objects
john owns
- house1
will owns
- house1
when automapper maps each person correctly, when maps house1 2 different instances!!
so have 2 copies of house1. john owns house1 (#1) , owns house1 (#2).
they not linked anymore.
is there way keep relations existed?
thanks.
edited: have this:
a document contains list of childdocuments. each childdocument has list of designables (rectangles, lines, ellipses…) , especial designable called childdocumentadapter contains anoother childdocument. trouble, can reference childdocument.
if i'm understanding question, you're performing 2 separate mapping operations - 1 john, will.
@sunny right. automapper not designed this. each call make mapper.map()
typically independent of other. using same instance of houselistconverter, benefit of caching mapped houses in dictionary. have either register globally or pass option mapping calls want grouped together. that's not work, it's hiding important implementation detail deep within converter.
if map both john , in 1 operation, putting them collection, output want without need custom converter or resolver.
it may easier alternative other people similar problem.
public void maplistofpeoplewithsamehouse() { mapper.createmap<person, persondto>(); mapper.createmap<house, housedto>(); var people = new list<person>(); var house = new house() { address = "123 main" }; people.add(new person() { name = "john", houses = new list<house>() { house } }); people.add(new person() { name = "will", houses = new list<house>() { house } }); var peopledto = mapper.map<list<persondto>>(people); assert.isnotnull(peopledto[0].houses); assert.aresame(peopledto[0].houses[0], peopledto[1].houses[0]); }
Comments
Post a Comment