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

前端 未结 2 1298
爱一瞬间的悲伤
爱一瞬间的悲伤 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条回答
  • 2020-12-30 12:10

    You can use the AfterMap() function of AutoMapper, like this:

    Mapper.CreateMap<ParentDto, Parent>()
          .ForMember(m => m.Children, o => o.Ignore()) // To avoid automapping attempt
          .AfterMap((p,o) => { o.Children = ToISet<ChildDto, Child>(p.Children); });
    

    AfterMap() allows for more fine-grained control of some important aspects of NHibernate child collections handling (like replacing existing collections content instead of overwriting the collections reference as in this simplified example).

    0 讨论(0)
  • 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<ChildDto> to ISet<Child>, which can be generalized to a mapping from IEnumerable<TSource> to ISet<TDestination> and not IEnumerable<T> to ISet<T>. 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<TDestination> ToISet<TSource, TDestination>(IEnumerable<TSource> source)
    {
        ISet<TDestination> set = null;
        if (source != null)
        {
            set = new HashSet<TDestination>();
    
            foreach (TSource item in source)
            {
                set.Add(Mapper.Map<TSource, TDestination>(item));
            }
        }
        return set;
    }
    

    You can then change the map definition as follows:

    Mapper.CreateMap<ParentDto, Parent>().ForMember(m => m.Children,
              o => o.MapFrom(p => ToISet<ChildDto, Child>(p.Children)));
    
    0 讨论(0)
提交回复
热议问题