I'm trying to find a way of configuring AutoMapper to set a property in a destination object with a reference of its source parent object. The code below shows what I'm trying to achieve. I'm moving data into the Parent & Child instances from the data objects. The mapping works fine to create the List collection with correct data but I need to have a ForEach to assign the parent instance reference.
public class ParentChildMapper { public void MapData(ParentData parentData) { Mapper.CreateMap<ParentData, Parent>(); Mapper.CreateMap<ChildData, Child>(); //Populates both the Parent & List of Child objects: var parent = Mapper.Map<ParentData, Parent>(parentData); //Is there a way of doing this in AutoMapper? foreach (var child in parent.Children) { child.Parent = parent; } //do other stuff with parent } } public class Parent { public virtual string FamilyName { get; set; } public virtual IList<Child> Children { get; set; } } public class Child { public virtual string FirstName { get; set; } public virtual Parent Parent { get; set; } } public class ParentData { public string FamilyName { get; set; } public List<Child> Children { get; set; } } public class ChildData { public string FirstName { get; set; } }
By default, AutoMapper only recognizes public members. It can map to private setters, but will skip internal/private methods and properties if the entire property is private/internal.
So, the AutoMapper Ignore() method is used when you want to completely ignore the property in the mapping. The ignored property could be in either the source or the destination object.
The built-in enum mapper is not configurable, it can only be replaced. Alternatively, AutoMapper supports convention based mapping of enum values in a separate package AutoMapper.
Use AfterMap. Something like this:
Mapper.CreateMap<ParentData, Parent>() .AfterMap((s,d) => { foreach(var c in d.Children) c.Parent = d; });
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With