-
Notifications
You must be signed in to change notification settings - Fork 55
Expand file tree
/
Copy pathShouldUseDeclaringTypeForInstanceMethodCalls.cs
More file actions
83 lines (73 loc) · 2.65 KB
/
ShouldUseDeclaringTypeForInstanceMethodCalls.cs
File metadata and controls
83 lines (73 loc) · 2.65 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using Xunit;
namespace AutoMapper.Extensions.ExpressionMapping.UnitTests
{
public class ShouldUseDeclaringTypeForInstanceMethodCalls
{
[Fact]
public void MethodInfoShouldRetainDeclaringTypeInMappedExpression()
{
//Arrange
var config = ConfigurationHelper.GetMapperConfiguration
(
cfg =>
{
cfg.CreateMap<EntityModel, Entity>();
cfg.CreateMap<Entity, EntityModel>();
}
);
config.AssertConfigurationIsValid();
var mapper = config.CreateMapper();
Expression<Func<Entity, bool>> filter = e => e.SimpleEnum.HasFlag(SimpleEnum.Value3);
EntityModel entityModel1 = new() { SimpleEnum = SimpleEnumModel.Value3 };
EntityModel entityModel2 = new() { SimpleEnum = SimpleEnumModel.Value2 };
//act
Expression<Func<EntityModel, bool>> mappedFilter = mapper.MapExpression<Expression<Func<EntityModel, bool>>>(filter);
//assert
Assert.Equal(typeof(Enum), HasFlagVisitor.GetasFlagReflectedType(mappedFilter));
Assert.Single(new List<EntityModel> { entityModel1 }.AsQueryable().Where(mappedFilter));
Assert.Empty(new List<EntityModel> { entityModel2 }.AsQueryable().Where(mappedFilter));
}
public enum SimpleEnum
{
Value1,
Value2,
Value3
}
public record Entity
{
public int Id { get; set; }
public SimpleEnum SimpleEnum { get; set; }
}
public enum SimpleEnumModel
{
Value1,
Value2,
Value3
}
public record EntityModel
{
public int Id { get; set; }
public SimpleEnumModel SimpleEnum { get; set; }
}
public class HasFlagVisitor : ExpressionVisitor
{
public static Type GetasFlagReflectedType(Expression expression)
{
HasFlagVisitor hasFlagVisitor = new();
hasFlagVisitor.Visit(expression);
return hasFlagVisitor.HasFlagReflectedType;
}
protected override Expression VisitMethodCall(MethodCallExpression node)
{
if (node.Method.Name == "HasFlag")
HasFlagReflectedType = node.Method.ReflectedType;
return base.VisitMethodCall(node);
}
public Type HasFlagReflectedType { get; private set; }
}
}
}