0

I am setting up a mapping between my models and my view models and I'm trying to map from an ICollection to class that derives from List

I have tried to make a mapping between my ListItemClassVM and ICollection but get an error 'Argument types do not match'

Option one mapping works with this:

public class ParentVM
{
    public List<ListItemClass> ListItemClasses { get; set; }
}

Option two mapping not working:

public class ParentVM
{
    public ListItemClassVM ListItemClasses { get; set; }
}

public ListItemClassVM : List<ListItemClass>
{

}

Mapping Setup:

public ModelClass_ParentVM_Profile()
    {
        CreateMap<ModelClass, ParentVM>()
            .ForMember(d => d.ListItemClasses, o => o.MapFrom(i => i.ModelCollection))
            ;

        CreateMap<ParentVM, ModelClass>()
            ;

    }

trying to setup the mapping so option two will map.

David Molyneux
  • 304
  • 2
  • 12
  • I'd [advise against deriving](https://stackoverflow.com/questions/21692193/why-not-inherit-from-listt) from `List` if you can help it. – ProgrammingLlama Jun 12 '19 at 09:03
  • @John Can you explaing why? Deriving from List is the only maintainable solution when you have to extend List. – user743414 Jun 12 '19 at 10:38
  • @user Largely because I feel this is often done to store information that's related to the list items. For example, a Person/Jobs relationship should not be represented as `public class Person: List { public string Name { get; set; } }`, because a Person is more than a list of jobs. A person can have jobs, but they are not jobs. Admittedly OP might not be doing this, but this is often what people do, and as suggested by @m-y in the linked post, OP could inherit from Collection if OP really wants to extend it. – ProgrammingLlama Jun 13 '19 at 02:25
  • @John Ah okay, I understand what you mean. – user743414 Jun 13 '19 at 07:23
  • @john thanks for the link interesting read didn't know this could cause performance issues. Main reason I was looking at this was a slight misunderstanding on my part I was looking at making a MVC Editor Template and thought EditorFor Linked on model type (its not its property name) and thought the List/Collection was giving an issue. Now I'm intrigued as to why Automapper sees this setup as different. – David Molyneux Jun 13 '19 at 11:25

1 Answers1

0

I think that there are more way to reach the solution, but you can't escape from a manual transposition from ICollection< ListItemClass > to ListItemClassVM. The simplier way maybe is to add to your ListItemClassVM a constructor that accepts an ICollection< ListItemClass > and initialize itself with the elements in ICollection, then you could do something like:

 CreateMap<ModelClass, ParentVM>()
        .ForMember(d => d.ListItemClasses, o => o.MapFrom(i =>new ListItemClassVM (i.ModelCollection)))
        ;
Sycraw
  • 543
  • 3
  • 17