Skip to content

Commit 2e4ea0c

Browse files
authored
Handling local constant expression. (#181)
1 parent 9f77f08 commit 2e4ea0c

File tree

2 files changed

+52
-0
lines changed

2 files changed

+52
-0
lines changed

src/AutoMapper.Extensions.ExpressionMapping/XpressionMapperVisitor.cs

+3
Original file line numberDiff line numberDiff line change
@@ -538,6 +538,9 @@ protected override Expression VisitConstant(ConstantExpression node)
538538
return base.VisitConstant(Expression.Constant(Mapper.MapObject(node.Value, node.Type, newType), newType));
539539
//Issue 3455 (Non-Generic Mapper.Map failing for structs in v10)
540540
//return base.VisitConstant(Expression.Constant(Mapper.Map(node.Value, node.Type, newType), newType));
541+
542+
if (typeof(Expression).IsAssignableFrom(node.Type))
543+
return Expression.Constant(this.Visit((Expression)node.Value), newType);
541544
}
542545
return base.VisitConstant(node);
543546
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
1+
using System;
2+
using System.Collections.Generic;
3+
using System.Linq;
4+
using System.Linq.Expressions;
5+
using Xunit;
6+
7+
namespace AutoMapper.Extensions.ExpressionMapping.UnitTests
8+
{
9+
public class CanMapExpressionWithLocalExpressionConstant
10+
{
11+
[Fact]
12+
public void Map_expression_wchich_includes_local_constant()
13+
{
14+
//Arrange
15+
var config = new MapperConfiguration
16+
(
17+
cfg =>
18+
{
19+
cfg.CreateMap<EntityModel, Entity>();
20+
cfg.CreateMap<Entity, EntityModel>();
21+
}
22+
);
23+
config.AssertConfigurationIsValid();
24+
var mapper = config.CreateMapper();
25+
List<Entity> source = [
26+
new Entity { Id = 1 },
27+
new Entity { Id = 3 }
28+
];
29+
30+
//act
31+
Expression<Func<EntityModel, bool>> filter = f => f.Id > 2;
32+
Expression<Func<IQueryable<EntityModel>, IQueryable<EntityModel>>> queryableExpression = q => q.Where(filter);
33+
Expression<Func<IQueryable<Entity>, IQueryable<Entity>>> queryableExpressionMapped = mapper.MapExpression<Expression<Func<IQueryable<Entity>, IQueryable<Entity>>>>(queryableExpression);
34+
35+
//assert
36+
Assert.Equal(1, queryableExpressionMapped.Compile()(source.AsQueryable()).Count());
37+
}
38+
39+
public record Entity
40+
{
41+
public int Id { get; init; }
42+
}
43+
44+
public record EntityModel
45+
{
46+
public int Id { get; init; }
47+
}
48+
}
49+
}

0 commit comments

Comments
 (0)