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

前端 未结 1 1971
广开言路
广开言路 2021-02-09 06:18

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; s         


        
相关标签:
1条回答
  • 2021-02-09 07:16

    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)

    0 讨论(0)
提交回复
热议问题