使用AutoMapper为投影创建LINQ表达式



我会使用AutoMapper创建一个与LINQ一起使用的表达式(例如LINQ to SQL):

void Main()
{
    Mapper.CreateMap<Person, PersonDto>();
    Mapper.Engine.CreateMapExpression<Person, PersonDto>().ToString().Dump();
}
public class Person
{
    public string Name { get; set; }
    public IEnumerable<Person> Children { get; set; }
}
public class PersonDto
{
    public string Name { get; set; }
    public IEnumerable<PersonDto> Children { get; set; }
}

但是在映射"Children"属性时发生了StackOverflowException(我过去已经给Jimmy写过信)。

作者告诉我们,问题是根类有一个自引用,但许多LINQ提供程序都不支持它。

如果根类没有自引用,则AutoMapper 3的问题是另一个,因为生成的LINQ表达式是:

x => new PersonDto() { Name = x.Name, Children = x.Children.Select(y => new AddressDto { Name = y.Name })} 

代替:

x => new PersonDto() { Name = x.Name, Children = IIF((x.Children == null), null, x.Children.Select(y => new AddressDto { Name = y.Name }))}

因此,如果根类的子属性为null,则投影将失败。

目前无法将AutoMapper用于此目的。

最新更新