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 simply map an NHibernate ISet to IList using AutoMapper and Map IList to ICollection through AutoMapper but still no joy.
I have a data object that looks like:
public class Parent
{
public virtual ISet<Child> Children {get; set; }
}
And a business object that looks like:
public class ParentDto
{
public IList<ChildDto> Children {get; set; }
}
Using AutoMapper to map from Data to Business works fine:
...
Mapper.CreateMap<Parent, ParentDto>();
Mapper.CreateMap<Child, ChildDto>();
...
ParentDto destination = CWMapper.Map<Parent, ParentDto>(source);
But when I come to Mapping from Business to Data I get the error:
...
Mapper.CreateMap<ParentDto, Parent>();
Mapper.CreateMap<ChildDto, Child>();
...
Parent destination = CWMapper.Map<ParentDto, Parent>(source);
Unable to cast object of type 'System.Collections.Generic.List' to ''Iesi.Collections.Generic.ISet'
I added a custom mapping:
Mapper.CreateMap<ParentDto, Parent>()
.ForMember(m => m.Children, o => o.MapFrom(s => ToISet<ChildDto>(s.Children)));
private static ISet<T> ToISet<T>(IEnumerable<T> list)
{
Iesi.Collections.Generic.ISet<T> set = null;
if (list != null)
{
set = new Iesi.Collections.Generic.HashedSet<T>();
foreach (T item in list)
{
set.Add(item);
}
}
return set;
}
But I still get the same error. Any help would be greatly apriciated!