SamIAm
SamIAm

Reputation: 2489

How can I map a parent to child using AutoMapper?

I have the following classes:

public class Parent {
    string id;
    Child child;
}

public class Child {
    string Name;
}

Essentially I would like to do an Automapper configuration that will allow me to map a Parent into the Child. How can I do that ?

var parent = GetParent();
var child = Mapper.Map<Child>(parent);

Is there a method available to do this without mapping the members one by one using

.ForMember(d=> d.Name, o=> o.MapFrom(src => src.child.Name));

Reasons:

1) There are multiple members in the child and creating multiple .ForMembers() seems messy.

2) Mapper.Map() is used instead of directly accessing the object because this is done a parent generic provider class that uses mapping configurations.

Upvotes: 2

Views: 3681

Answers (1)

Thorin Jacobs
Thorin Jacobs

Reputation: 300

In the simple case provided,

.ProjectUsing(x => x.Child)

should accomplish what you're trying to do here.

Sample code is below - I've included an Id on the child to verify that only fields from the Parent.Child will be mapped over to the new child.

Note that this does not combine with .MapFrom() - so if you had, for instance, a ParentId property on the child you'd need to do some additional manual mapping to get that from the parent to the child.

Regarding multiple .ForMember()s seeming messy - agree that it can pile up if you have a large number of mappings going on, but in my experience it can be beneficial in preventing rename refactors from breaking your mappings. Strongly encourage using a configuration validation unit test to ensure that such refactors don't break your mappings. Hope that helps!

    class Program
{
    static void Main(string[] args)
    {
        Mapper.Initialize(MapperConfiguration);

        var parent = new Parent()
        {
            Id = "a",
            Child = new Child()
            {
                Name = "ChildA",
                Id = 1
            }
        };

        var child = Mapper.Map<Child>(parent);

        Console.Read();
    }

    private static void MapperConfiguration(IMapperConfigurationExpression mapper)
    {
        mapper.CreateMap<Parent, Child>()
            .ProjectUsing(x => x.Child);
    }

    public class Parent
    {
        public string Id { get; set; }
        public Child Child { get; set; }
    }

    public class Child
    {
        public string Name { get; set; }
        public int Id { get; set; }
    }
}

Upvotes: 1

Related Questions