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?
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:
List<string>
etc.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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With