Skip to content

Support generic type argument inference when mapping method calls #99

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 1 commit into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -68,7 +68,10 @@ private MethodCallExpression GetConvertedMethodCall(MethodCallExpression node)
if (!node.Method.IsGenericMethod)
return node;
var convertedArguments = Visit(node.Arguments);
var convertedMethodArgumentTypes = node.Method.GetGenericArguments().Select(t => GetConvertingTypeIfExists(node.Arguments, t, convertedArguments)).ToArray();
var genericMethodCall = node.Method.GetGenericMethodDefinition();
var convertedMethodArgumentTypes = TypeMatcher.InferGenericArguments(genericMethodCall,
convertedArguments.Select(expr => expr.Type));

var convertedMethodCall = node.Method.GetGenericMethodDefinition().MakeGenericMethod(convertedMethodArgumentTypes);
return Call(convertedMethodCall, convertedArguments);
}
Expand Down
59 changes: 59 additions & 0 deletions src/AutoMapper.Extensions.ExpressionMapping/TypeMatcher.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;

namespace AutoMapper.Extensions.ExpressionMapping
{
public static class TypeMatcher
{
public static Type[] InferGenericArguments(MethodInfo method, IEnumerable<Type> constructedArgumentTypes)
{
return new TypeInference(method, constructedArgumentTypes).Result;
}

private class TypeInference
{
public Type[] Result { get; }
private readonly HashSet<Type> _matched;

public TypeInference(MethodInfo method, IEnumerable<Type> constructedArgumentTypes)
{
Result = method.GetGenericArguments();
_matched = new HashSet<Type>();

foreach (var pair in constructedArgumentTypes.Zip(method.GetParameters().Select(p => p.ParameterType),
(arg, param) => new {Argument = arg, Parameter = param}))
{
MatchGenericParameter(pair.Argument, pair.Parameter);
if (_matched.Count == Result.Length) return;
}

throw new Exception($"Failed to infer generic arguments for {method} using argument types {string.Join(", ", constructedArgumentTypes)}.");
}

private void MatchGenericParameter(Type argumentType, Type parameterType)
{
if (parameterType.IsGenericParameter && _matched.Add(parameterType))
{
for (var i = 0; i < Result.Length; i++)
{
if (Result[i] == parameterType)
{
Result[i] = argumentType;
return;
}
}
}
else if (parameterType.IsGenericType && argumentType.IsGenericType)
{
foreach (var pair in argumentType.GetGenericArguments().Zip(parameterType.GetGenericArguments(),
(arg, param) => new {Argument = arg, Parameter = param}))
{
MatchGenericParameter(pair.Argument, pair.Parameter);
}
}
}
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,104 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using Shouldly;
using Xunit;

namespace AutoMapper.Extensions.ExpressionMapping.UnitTests
{
public class MappingToNullablePropertyUsingUseAsDataSource
{
[Fact]
public void When_Apply_OrderBy_Clause_Over_Queryable_As_Data_Source()
{
// Arrange
var mapper = CreateMapper();

var models = new List<Model>()
{
new Model {Value = 1},
new Model {Value = 2}
};

var queryable = models.AsQueryable();

Expression<Func<DTO, int?>> dtoPropertySelector = (dto) => dto.Value;

// Act
var result = queryable.UseAsDataSource(mapper).For<DTO>().OrderBy(dtoPropertySelector).ToList();

// Assert
result.ShouldNotBeNull();
result.Count.ShouldBe(2);
}

[Fact]
public void When_Apply_Where_Clause_Over_Queryable_As_Data_Source()
{
// Arrange
var mapper = CreateMapper();

var models = new List<Model> {new Model {Value = 1}, new Model {Value = 2}};

var queryable = models.AsQueryable();

Expression<Func<DTO, bool>> dtoPropertyFilter = (dto) => dto.Value == 1;

// Act
var result = queryable.UseAsDataSource(mapper).For<DTO>().Where(dtoPropertyFilter).ToList();

// Assert
result.ShouldNotBeNull();
result.Count.ShouldBe(1);
}

[Fact]
public void When_Apply_Where_Clause_Over_Queryable_As_Data_Source_DateTimeOffset()
{
// Arrange
var mapper = CreateMapper();

var models = new List<Model>
{
new Model {Value = 1, Timestamp = DateTimeOffset.Now},
new Model {Value = 2, Timestamp = DateTimeOffset.Now.AddDays(1)}
};

var queryable = models.AsQueryable();

Expression<Func<DTO, bool>> dtoPropertyFilter = (dto) => dto.Timestamp > DateTimeOffset.Now;

// Act
var result = queryable.UseAsDataSource(mapper).For<DTO>().Where(dtoPropertyFilter).ToList();

// Assert
result.ShouldNotBeNull();
result.Count.ShouldBe(1);
}

private static IMapper CreateMapper()
{
var mapperConfig = new MapperConfiguration(cfg =>
{
cfg.CreateMap<Model, DTO>();
});

var mapper = mapperConfig.CreateMapper();
return mapper;
}

private class Model
{
public DateTimeOffset Timestamp { get; set; }
public int Value { get; set; }
}

private class DTO
{
public DateTimeOffset? Timestamp { get; set; }
public int? Value { get; set; }
}

}
}