I am trying to use AutoMapper to map DTO objects (data) retrieved from a web service to my business objects. The DTO root object contains a collection of child objects. My business object also has a child collection of child business objects. To make AutoMapper work, I had to include setter in the collection property in my business object, or the collection would always be empty. Also, I had to add a default constructor to the collection type. So, it seems to me that AutoMapper creates an instance of a new collection object, populating it and setting it as a collection property of my business object.
While all of this is good and good, I have additional logic that needs to be connected when creating the collection, and the default constructor defeats the target. Essentially, I establish a parent-child relationship and hook some events so that they bubble from child to parent.
What I would like to do is that AutoMapper simply maps the children from the DTO collection to the existing collection of my BO. In other words, skip creating a new collection and just use the one that already has the business object.
Is there any way to easily accomplish this?!?!?
UPDATE
Perhaps the best question and a simpler solution to my problem is if you can determine the arguments that AutoMapper will pass to the collection when creating the instance? My child collection is defined as follows:
public class ChildCollection : Collection<ChildObjects>
{
public ChildCollection(ParentObject parent) { Parent = parent; }
}
AutoMapper , PERFECT!
:
public class ParentObject
{
private ChildCollection _children;
public ChildCollection Children
{
get
{
if (_children == null) _children = new ChildCollection(this);
return _children;
}
}
}
public class ParentDTO
{
public ICollection<ChildDTO> Children { get; set; }
}
public class ChildDTO
{
public String SomeProperty { get; set; }
}
AutoMapper :
Mapper.CreateMap<ParentDTO, ParentObject>();
Mapper.CreateMap<ChildDTO, ChildObject>();
, setter Children ParentObject ( ) ChildCollection. , , , AutoMapper . - :
Mapper.CreateMap<ParentDTO, ParentObject>()
.ForMember(obj => obj.Children,
opt.MapFrom(dto => dto.Children)
.ConstructUsing(col => new ChildCollection(obj)));
, "obj", ParentObject, .