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

时间:2013-11-19 11:03:29

标签: c# linq automapper projection

我会使用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; }
}

但是StackOverflowException映射了“Children”属性(过去我已经写过Jimmy)。

1 个答案:

答案 0 :(得分:0)

作者告诉我的问题是根类有自引用,但许多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。