AutoMapper/AutoMapper — Issue #159: Problem with mapping collections in LINQ
Author: rosieks
Created: 2011-12-20 11:09:03+00:00
State: open

Hi, Automapper has problem with projecting collections in mapped object. It throw exception with message: Sequence contains no elements. The following code illustrate problem:

using System.Collections.Generic;
using System.Linq;
using AutoMapper;
using AutoMapper.QueryableExtensions;
namespace ConsoleApplication1
{
public class EntryViewModel
{
public int Id { get; set; }
public string Name { get; set; }
public byte[] Timestamp { get; set; }
public IEnumerable Comments { get; set; }
}

public class CommentViewModel
{
public int Id { get; set; }
public string Content { get; set; }
public bool Accepted { get; set;}
}

public class Entry
{
public int Id { get; set; }
public string Name { get; set; }
public byte[] Timestamp { get; set; }
public ICollection Comments { get; set; }
}

public class Comment
{
public int Id { get; set; }
public string Content { get; set; }
public bool Accepted { get; set; }
}

class Program
{
static void Main(string[] args)
{
Mapper.CreateMap();
Mapper.CreateMap()
.ForMember(d => d.Comments, o => o.MapFrom(s => s.Comments.Where(c => c.Accepted)));

new Entry[0].AsQueryable().Project().To().ToArray();
}
}
}