AutoMapper/AutoMapper — Issue #146: QueryableExtensions: projecting fails when source and destination contain members that are also mapped (not flattening)
Author: StephenRedd
Created: 2011-11-10 23:57:12+00:00
State: open

Attempting to perform a non-flattening projection against an IQueryable where the destination contains a member that is a complex mapped type also. In other words, the DTOs are a hierarchy that mirrors hierarchy of the source.

Given these objects for example:

public class Toaster
{
public string Name { get; set; }
public virtual ToasterManufacturer Manufacturer { get; set; }
}
public class ToasterManufacturer
{
public string Name { get; set; }
}
public class ToasterDto
{
public string Name { get; set; }
public ToasterManufacturerDto Manufacturer { get; set; }
}
public class ToasterManufacturerDto
{
public string Name { get; set; }
}

Then given this method

public void TestTheProjection()
{
Mapper.CreateMap();
Mapper.CreateMap();

var toasters = new List();
toasters.Add(new Toaster() { Name = "toaster1", Manufacturer = new ToasterManufacturer() { Name = "manufact1" } });

var tQuery = toasters.AsQueryable();
var projection = tQuery.Project().To();
//do other stuff
}

Will Produce this exception:

Test method AutoapperTests.ProjectionExpressionTest.TestTheProjection threw exception:
System.ArgumentException: Expression of type 'AutoapperTests.ProjectionExpressionTest+Toaster' cannot be used for parameter of type 'AutoapperTests.ProjectionExpressionTest+ToasterManufacturer'

And this StackTrace:

System.Linq.Expressions.Expression.ValidateOneArgument(MethodBase method, ExpressionType nodeKind, Expression arg, ParameterInfo pi)
System.Linq.Expressions.Expression.ValidateArgumentTypes(MethodBase method, ExpressionType nodeKind, ReadOnlyCollection`1& arguments)
System.Linq.Expressions.Expression.Invoke(Expression expression, IEnumerable`1 arguments)
System.Linq.Expressions.Expression.Invoke(Expression expression, Expression[] arguments)
AutoMapper.MappingEngine.CreateMapExpression(Type typeIn, Type typeOut) in C:\Somewhere\AutoMapper-AutoMapper-e9c90c8\src\AutoMapper\MappingEngine.cs: line 268
AutoMapper.MappingEngine.b__7[TSource,TDestination](TypePair tp) in C:\Somewhere\AutoMapper-AutoMapper-e9c90c8\src\AutoMapper\MappingEngine.cs: line 169
System.Collections.Concurrent.ConcurrentDictionary`2.GetOrAdd(TKey key, Func`2 valueFactory)
AutoMapper.MappingEngine.CreateMapExpression[TSource,TDestination]() in C:\Somewhere\AutoMapper-AutoMapper-e9c90c8\src\AutoMapper\MappingEngine.cs: line 166
AutoMapper.QueryableExtensions.ProjectionExpression`1.To[TResult]() in C:\Somewhere\AutoMapper-AutoMapper-e9c90c8\src\AutoMapper\QueryableExtensions.cs: line 40
AutoapperTests.ProjectionExpressionTest.TestTheProjection() in C:\Somewhere\AutoMapper-AutoMapper-e9c90c8\src\TestProject1\ProjectionExpressionTest.cs: line 81