I would use AutoMapper to create an expression to use with LINQ (e.g. 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; }
}
But a StackOverflowException occurs mapping the "Children" property (I had already written to Jimmy in the past).
The author told that the problem is that the root class has a self reference, but it's not supported by many LINQ providers.
If the root class has not self-references the problem is another with AutoMapper 3, because the produced LINQ expression is:
x => new PersonDto() { Name = x.Name, Children = x.Children.Select(y => new AddressDto { Name = y.Name })}
Instead of:
x => new PersonDto() { Name = x.Name, Children = IIF((x.Children == null), null, x.Children.Select(y => new AddressDto { Name = y.Name }))}
So if the child property of the root class is null, the projection will fail.
At the moment is not possible to use AutoMapper for this purpose.