title: Using AutoMapper to Map IList<TSource> to (Iesi.Collections.Generic) ISet<TDestination>
body: <p>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 <a href="https://stackoverflow.com/questions/1703152/using-automapper-by-jimmy-bogard-with-nhibernate">How to simply map an NHibernate ISet to IList using AutoMapper</a> and <a href="https://stackoverflow.com/questions/5483174/map-ilist-to-icollection-through-automapper">Map IList to ICollection through AutoMapper</a> but still no joy.</p>
  
  <p>I have a data object that looks like:</p>
  
  <pre><code>public class Parent
  {
     public virtual ISet&lt;Child&gt; Children  {get; set; }
  }
  </code></pre>
  
  <p>And a business object that looks like:</p>
  
  <pre><code>public class ParentDto
  {
     public IList&lt;ChildDto&gt; Children  {get; set; }
  }
  </code></pre>
  
  <p>Using AutoMapper to map from Data to Business works fine:</p>
  
  <pre><code>...
  Mapper.CreateMap&lt;Parent, ParentDto&gt;();
  Mapper.CreateMap&lt;Child, ChildDto&gt;();
  ...
  
  ParentDto destination = CWMapper.Map&lt;Parent, ParentDto&gt;(source);
  </code></pre>
  
  <p>But when I come to Mapping from Business to Data I get the error:</p>
  
  <pre><code>...
  Mapper.CreateMap&lt;ParentDto, Parent&gt;();
  Mapper.CreateMap&lt;ChildDto, Child&gt;();
  ...
  
  Parent destination = CWMapper.Map&lt;ParentDto, Parent&gt;(source);
  </code></pre>
  
  <blockquote>
    <p>Unable to cast object of type 'System.Collections.Generic.List' to ''Iesi.Collections.Generic.ISet'</p>
  </blockquote>
  
  <p>I added a custom mapping:</p>
  
  <pre><code>Mapper.CreateMap&lt;ParentDto, Parent&gt;()
        .ForMember(m =&gt; m.Children, o =&gt; o.MapFrom(s =&gt; ToISet&lt;ChildDto&gt;(s.Children)));
  
  private static ISet&lt;T&gt; ToISet&lt;T&gt;(IEnumerable&lt;T&gt; list)
      {
          Iesi.Collections.Generic.ISet&lt;T&gt; set = null;
  
          if (list != null)
          {
              set = new Iesi.Collections.Generic.HashedSet&lt;T&gt;();
  
              foreach (T item in list)
              {
                  set.Add(item);
              }
          }
  
          return set;
      }
  </code></pre>
  
  <p>But I still get the same error. Any help would be greatly apriciated!</p>