Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to assign parent reference to a property in a child with AutoMapper

Tags:

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; } } 
like image 966
Sixto Saez Avatar asked Dec 07 '10 13:12

Sixto Saez


People also ask

Does AutoMapper map private properties?

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.

How do I ignore source property AutoMapper?

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.

Can AutoMapper map enums?

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.


1 Answers

Use AfterMap. Something like this:

Mapper.CreateMap<ParentData, Parent>()     .AfterMap((s,d) => {         foreach(var c in d.Children)             c.Parent = d;         }); 
like image 74
PatrickSteele Avatar answered Oct 23 '22 19:10

PatrickSteele