views:

35

answers:

2

I have a class Foos:

public class Foos
{
    public string TypeName;

    public IEnumerable<int> IDs;
}

Is it possible to map it with AutoMapper to IList of Foo objects?

public class Foo
{
    public string TypeName;

    public int ID;
}
+2  A: 

here's the solution with the ValueInjecter

    var list = new List<Foo>();
    foos.IDs.AsParallel().ForAll(id =>
                                     {
                                         var foo = new Foo();
                                         foo.InjectFrom(foos);
                                         foo.ID = id;
                                         list.Add(foo);
                                     });
Omu
Thank you for the example. I don't quite understand what is the difference between your code and linq .Select() function combained with a mapping foos to foo. My problem is that I need the mapping to convert foos object into IList of foo objects. The mapping is defined across application in a Profile file so the list created there will not work. Also I can't create list object in the place where I do mapping as it is generic class and can perform mappings for many types that do not require convertion to list. Let me know if there is something I'm missing in your solution.
Woj
well, my solution does exactly what you asked for, if you would have showed something else I would have showed how to do that thing
Omu
+1  A: 

Omu's answer gaved me an idea how to solve the problem (+1 for suggestion). I've used ConstructUsing() method and it worked for me:

    private class MyProfile : Profile
    {
        protected override void Configure()
        {
            CreateMap<Foos, Foo>()
                .ForMember(dest => dest.ID, opt => opt.Ignore());
            CreateMap<Foos, IList<Foo>>()
                .ConstructUsing(x => x.IDs.Select(y => CreateFoo(x, y)).ToList());                
        }

        private Foo CreateFoo(Foos foos, int id)
        {
            var foo = Mapper.Map<Foos, Foo>(foos);
            foo.ID = id;
            return foo;
        }
    }
Woj
good for you, mine looks simpler though :)
Omu