Using AutoMapper to Map IList to (Iesi.Collections.Generic) ISet

前端 未结 2 1302
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-12-30 11:41

I have been trying to solve this issue for a day now and have got no where so am hoping someone might have solved this before. The closest I found to a solution was How to s

2条回答
  •  萌比男神i
    2020-12-30 12:21

    This is because the source and destination generic type parameters are not the same in the source and target properties that you are mapping. The mapping you need is from IEnumerable to ISet, which can be generalized to a mapping from IEnumerable to ISet and not IEnumerable to ISet. You need to take this into account in your conversion function (actually you have the correct answer in the title of your question..).

    The ToISet method should be something like the one posted below. It uses AutoMapper as well to map ChildDto to Child.

    private static ISet ToISet(IEnumerable source)
    {
        ISet set = null;
        if (source != null)
        {
            set = new HashSet();
    
            foreach (TSource item in source)
            {
                set.Add(Mapper.Map(item));
            }
        }
        return set;
    }
    

    You can then change the map definition as follows:

    Mapper.CreateMap().ForMember(m => m.Children,
              o => o.MapFrom(p => ToISet(p.Children)));
    

提交回复
热议问题