Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Automapper fails when projecting IQueryable<object> when object has a collection property

So, here's my situation. I've got a my two classes:

class FromClass
{
    public string[] Foo { get; set; }
}

class ToClass
{
    public string[] Foo { get; set; }
}

The classes have properties which are arrays. They could be List<T> or IEnumerable<T>, I get the same result in any of those cases.

I try to map from one to the other using the AutoMapper.QueryableExtensions:

class Program
{
    static void Main(string[] args)
    {
        // create a "From" object
        string[] anArray = new string[] { "a", "b" };
        FromClass anObject = new FromClass() { Foo = anArray };

        // make a queryable set that includes the "From" object
        IQueryable<FromClass> queryableObjects = (new FromClass[] { anObject }).AsQueryable();

        // set up AutoMapper
        Mapper.CreateMap<FromClass, ToClass>();
        Mapper.AssertConfigurationIsValid();

        // test plain mapping
        IQueryable<ToClass> test1 = queryableObjects.Select(o => Mapper.Map<FromClass, ToClass>(o));
            // success!

        // test queryable extensions
        IQueryable<ToClass> test2 = queryableObjects.Project().To<ToClass>();
            // InvalidOperationException: "Sequence contains no elements"

    }
}

Why does test2 throw an InvalidOperationException? If I make the type of Foo something that's not a collection, e.g. a string or some other class -- then everything works perfectly.

Am I doing something wrong? Not understanding something? Or have I hit a bug?

like image 406
Tobin Avatar asked Apr 24 '12 04:04

Tobin


1 Answers

I would say: this is a bug: see Github Issue 159.

The AutoMapper.QueryableExtensions uses Mapper.CreateMapExpression internally so if you write:

var expression = Mapper.CreateMapExpression<FromClass, ToClass>();

It will also fail with the same exception.

It seems Mapper.CreateMapExpression currently does not support:

  • generic collections of value types e.g. List<string> etc.
  • arrays of complex types or value types e.g string[], Bar[] etc.

But if you make your Foo to List<Item> it can work:

public class FromClass
{
    public List<Item> Foo { get; set; }
}

public class ToClass
{
    public List<Item> Foo { get; set; }
}

public class Item
{
    public string Bar { get; set; }
}

var list =  new List<Item> { new Item{ Bar = "a"}, new Item() { Bar= "b" }};
FromClass anObject = new FromClass() { Foo = list };
var queryableObjects = (new FromClass[] { anObject }).AsQueryable();
Mapper.CreateMap<FromClass, ToClass>();
Mapper.CreateMap<Item, Item>();
var test2 = queryableObjects.Project().To<ToClass>().ToArray();

You can comment on the above mentioned issue or create a new one with your code (it's a quite good repro of the bug)

like image 182
nemesv Avatar answered Oct 22 '22 15:10

nemesv