0

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

4
  • A person (name) can have more than one phone numbers... Aside from not showing any attempt, you haven't described what should happen in this scenario. Class C expects one number per one name. Commented Dec 11, 2015 at 16:25
  • Class C should provide all the records from the db. If we have records 1. Sam | 0786878768, 2. Sam|065765768, 3. Isaac | 8976897987, 4. Philip | 232342, GetContacts should fetch all 4 records. Commented Dec 11, 2015 at 16:28
  • That makes no sense. Class C can't provide all the records, IEnumerable<C> perhaps could, but you can't have a single instance represent multiple instances. Commented Dec 11, 2015 at 16:32
  • Yes I meant IList<C>, GetContacts return type is IList<C>. Will update my comment as well. Commented Dec 11, 2015 at 16:36

1 Answer 1

1

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 });
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks. I'll try this.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.