Husain
Husain

Reputation: 845

Automapper and Nested Object

Suppose I have the following classes

public class Parent {
    public int ParentId { get; set; }
    public List<Child> Children{get; set; }
    // other properties
}

public class Child {
    public int ChildId { get; set; }
    // other properties
}


public class ParentVm {
    public int ParentId { get; set; }
    public List<ChildVm> Children{get; set; }
    // other properties
}

public class ChildVm {
    public int ParentId { get; set; }
    public int ChildId { get; set; }
    // other properties
}

Parent parent = /*something*/
var parentVm = Mapper.Map<ParentVm>(parent);

In the ChildVm, there is property ParentId. How can I propagate that value to using automapper?

Upvotes: 0

Views: 302

Answers (1)

Tony Morris
Tony Morris

Reputation: 1007

I'm making some assumptions with your question.

  1. You are trying to map Parent to ParentVm (and Child to ChildVm).
  2. You are trying to map Parent.ParentId to ChildVm.ParentId.

If both of these are true, then the following code snippet (from LINQPad) should help you. Note the use of AfterMap in the first CreateMap.

void Main()
{
    var config = new MapperConfiguration(cfg =>
    {
        cfg.CreateMap<Parent, ParentVm>().AfterMap((s, d) =>
        {
            foreach (var child in d.Children)
            {
                child.ParentId = d.ParentId;
            }
        });
        cfg.CreateMap<Child, ChildVm>();
    });

    var mapper = config.CreateMapper();

    var parent = new Parent { ParentId = 1, Children = new List<Child>() };
    var child1 = new Child { ChildId = 1 };
    var child2 = new Child { ChildId = 2 };
    parent.Children.Add(child1);
    parent.Children.Add(child2);

    var parentVm = mapper.Map<Parent, ParentVm>(parent);
    parentVm.Dump();
}

public class Parent
{
    public int ParentId { get; set; }
    public List<Child> Children { get; set; }
    // other properties
}

public class Child
{
    public int ChildId { get; set; }
    // other properties
}


public class ParentVm
{
    public int ParentId { get; set; }
    public List<ChildVm> Children { get; set; }
    // other properties
}

public class ChildVm
{
    public int ParentId { get; set; }
    public int ChildId { get; set; }
    // other properties
}

Output:

LINQPad Dump Results

Upvotes: 3

Related Questions