AutoMapper is not mapping ICollection<T>

Viewed 132

I am searching a knowledge how to properly configure AutoMapper to Include ICollection types mapping also.

Take a look at example below. There are some entities with sample names:

    public abstract class Bar
    {
        public int Id { get; set; }
        public virtual Foo Item { get; set; }
    }
    public class Baz : Bar
    {
        public new virtual Foobar Item { get; set; }
    }
    public class Zoo : Baz
    {
        public new virtual Foobarbaz Item { get; set; }
    }
    public abstract class Foo
    {
        public ICollection<Bar> Items { get; set; }
    }
    public class Foobar : Foo
    {
        public new ICollection<Baz> Items { get; set; }
    }
    public class Foobarbaz : Foobar
    {
        public new ICollection<Zoo> Items { get; set; }
    }

and now i would like to map Foobarbaz to Foo including ICollection<Zoo> Items map to ICollection<Bar> Items is it possible to configure AutoMapper to map like that in one line like Mapper.Map<Foo>(foobarbaz);

I tried i.a. configure like that

            Mapper.CreateMap<Foobar, Foo>()
                        .Include<Foobarbaz, Foobar>();      
            Mapper.CreateMap<Foobarbaz, Foobar>();      
            Mapper.CreateMap<Baz, Bar>()
                .Include<Zoo, Baz>();
            Mapper.CreateMap<Zoo, Baz>();

with no success

actually working solution i found is to firstly map Foobarbaz into Foo and then using Linq map Items like below:

            Foo foo = Mapper.Map<Foo>(foobarbaz);    
            foo.Items = foobarbaz.Items.Select(f => Mapper.Map<Bar>(f)).ToList();

Finally I would like to achieve something which allows me to return base information (described by Foo class properties) no matter which nested type will I have.

Therefore I assumed I could override an abstract function defined in Bar that would return the parent of the Item list. For example having object of type Zoo by calling overriden function I'll return mapped its parent of class Foobarbaz to Foo with also mapped Items from Zoo to Bar.

I don't think it's stupid, and as I said before.. I had working solution but I'd like some advice on how to make it even better.

0 Answers
Related