techy
techy

Reputation: 135

Nested objects to one object using Automapper

Have a requirement to map name (Class A) and phone number (Class B) to Class C which has both Name and PhoneNumber. A person (name) can have more than one phone numbers.

public class A
{
    public int ID { get; set; }
    public string Name { get; set; }
    public virtual IList<B> B { get; set; }
}

public class B
{
    public int A_ID { get; set; }
    public string PhoneNumber { get; set; }
}

public class C
{
    public string Name { get; set; }
    public string PhoneNumber { get; set; }
}

Getting A class (which has B) details from the database and it needs to be mapped to Class C.

public class Activity
{
    public IList<C> GetContacts(string name)
    {
        using (ModelEntities ctx = new ModelEntities())
        {
            Mapper.CreateMap<A, C>();
            Mapper.CreateMap<B, C>();

            var result =
                ctx.A.SingleOrDefault(ss => ss.Name == name);

        }
    }
}

Can anyone help me to map using Automapper?

Thanks

Upvotes: 0

Views: 507

Answers (1)

Chris Pratt
Chris Pratt

Reputation: 239430

AutoMapper cannot map from a single instances to multiple instances. It either must be instance to instance or enumerable to enumerable. The best path forward I can see is to simply map your IList<B> to IList<C> and then back-fill the Name property. Something along the lines of:

var c = Mapper.Map<IList<C>>(a.B);
c.ToList().ForEach(m => m.Name = a.Name);

However, unless your mapping is hella more complex than this, AutoMapper is overkill. You could simply do:

var c = a.B.Select(b => new C { Name = a.Name, PhoneNumber = b.PhoneNumber });

Upvotes: 1

Related Questions