forked from MapsterMapper/Mapster
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathClassAdapter.cs
More file actions
294 lines (259 loc) · 13.6 KB
/
ClassAdapter.cs
File metadata and controls
294 lines (259 loc) · 13.6 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
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using Mapster.Models;
using Mapster.Utils;
namespace Mapster.Adapters
{
/// <summary>
/// Maps one class to another.
/// </summary>
/// <remarks>The operations in this class must be extremely fast. Make sure to benchmark before making **any** changes in here.
/// The core Adapt method is critically important to performance.
/// </remarks>
internal class ClassAdapter : BaseClassAdapter
{
protected override int Score => -200;
protected override bool CanMap(PreCompileArgument arg)
{
return arg.ExplicitMapping || arg.DestinationType.IsPoco();
}
protected override bool CanInline(Expression source, Expression? destination, CompileArgument arg)
{
if (!base.CanInline(source, destination, arg))
return false;
if (arg.MapType == MapType.MapToTarget)
return false;
var constructUsing = arg.GetConstructUsing();
if (constructUsing != null &&
constructUsing.Body.NodeType != ExpressionType.New &&
constructUsing.Body.NodeType != ExpressionType.MemberInit)
{
if (arg.MapType == MapType.Projection)
throw new InvalidOperationException("ConstructUsing for projection is support only New and MemberInit expression.");
return false;
}
//Ignore, IgnoreNullValue isn't supported by projection
if (arg.MapType == MapType.Projection)
return true;
if (arg.Settings.IgnoreNullValues == true)
return false;
if (arg.Settings.Ignore.Any(item => item.Value.Condition != null))
return false;
return true;
}
protected override Expression CreateInstantiationExpression(Expression source, Expression? destination, CompileArgument arg)
{
//new TDestination(src.Prop1, src.Prop2)
if (arg.DestinationType.isDefaultCtor() || arg.GetConstructUsing() != null)
if (arg.Settings.MapToConstructor == null)
return base.CreateInstantiationExpression(source, destination, arg);
ClassMapping? classConverter;
var ctor = arg.Settings.MapToConstructor as ConstructorInfo;
if (ctor == null)
{
var destType = arg.DestinationType.GetTypeInfo().IsInterface
? DynamicTypeGenerator.GetTypeForInterface(arg.DestinationType, arg.Settings.Includes.Count > 0)
: arg.DestinationType;
if (destType == null)
return base.CreateInstantiationExpression(source, destination, arg);
var constructors = destType.GetConstructors();
classConverter = constructors
.OrderByDescending(it => it.GetParameters().Length)
.Select(it => GetConstructorModel(it, true))
.Select(it => CreateClassConverter(source, it, arg, ctorMapping: true))
.FirstOrDefault(it => it != null);
if (classConverter == null && constructors.Length > 0)
classConverter = CreateClassConverter(source, GetConstructorModel(constructors[0], false), arg, ctorMapping: true);
}
else
{
var model = GetConstructorModel(ctor, false);
classConverter = CreateClassConverter(source, model, arg, ctorMapping:true);
}
if (classConverter == null)
return base.CreateInstantiationExpression(source, destination, arg);
return CreateInstantiationExpression(source, classConverter, arg, destination);
}
protected override Expression CreateBlockExpression(Expression source, Expression destination, CompileArgument arg)
{
//### !IgnoreNullValues
//dest.Prop1 = convert(src.Prop1);
//dest.Prop2 = convert(src.Prop2);
//### IgnoreNullValues
//if (src.Prop1 != null)
// dest.Prop1 = convert(src.Prop1);
//if (src.Prop2 != null)
// dest.Prop2 = convert(src.Prop2);
var classModel = GetSetterModel(arg);
var classConverter = CreateClassConverter(source, classModel, arg, destination);
var members = classConverter.Members;
var lines = new List<Expression>();
Dictionary<LambdaExpression, Tuple<List<Expression>, Expression>>? conditions = null;
foreach (var member in members)
{
var destMember = arg.MapType == MapType.MapToTarget || member.UseDestinationValue
? member.DestinationMember.GetExpression(destination)
: null;
Expression adapt;
// convert ApplyNullable Propagation for NotPrimitive Nullable types
if (member.Getter is ConditionalExpression cond && member.Getter.Type.IsNotPrimitiveNullableType()
&& !member.DestinationMember.Type.IsNullable())
{
var value = CreateAdaptExpression(cond.IfTrue.GetNotPrimitiveNullableValue(), member.DestinationMember.Type, arg, member, destMember);
adapt = Expression.Condition(cond.Test, value, member.DestinationMember.Type.CreateDefault());
}
else
adapt = CreateAdaptExpression(member.Getter, member.DestinationMember.Type, arg, member, destMember);
if (member.UseDestinationValue
&& member.DestinationMember.Type.IsMapsterImmutable()
&& member.DestinationMember.SetterModifier == AccessModifier.None)
{
if (member.DestinationMember is PropertyModel && arg.MapType != MapType.Projection)
adapt = SetValueTypeAutoPropertyByReflection(member, adapt, classModel);
else
continue;
if (adapt == Expression.Empty())
continue;
}
if (!member.UseDestinationValue)
{
if (arg.Settings.IgnoreNullValues == true && member.Getter.CanBeNull())
{
if (adapt is ConditionalExpression condEx)
{
if (condEx.Test is BinaryExpression {NodeType: ExpressionType.Equal} binEx &&
binEx.Left == member.Getter &&
binEx.Right is ConstantExpression {Value: null})
adapt = condEx.IfFalse;
}
adapt = member.DestinationMember.SetExpression(destination, adapt);
var condition = Expression.NotEqual(member.Getter, Expression.Constant(null, member.Getter.Type));
adapt = Expression.IfThen(condition, adapt);
}
else
{
//Todo Try catch block should be removed after pull request approved
try
{
if (member.DestinationMember.SetterModifier != AccessModifier.None)
{
var destinationPropertyInfo = (PropertyInfo)member.DestinationMember.Info!;
adapt = destinationPropertyInfo.IsInitOnly()
? SetValueByReflection(member, (MemberExpression)adapt)
: member.DestinationMember.SetExpression(destination, adapt);
}
}
catch (Exception e)
{
adapt = member.DestinationMember.SetExpression(destination, adapt);
}
}
}
else if (!adapt.IsComplex())
continue;
if (member.Ignore.Condition != null)
{
conditions ??= new Dictionary<LambdaExpression, Tuple<List<Expression>, Expression>>();
if (!conditions.TryGetValue(member.Ignore.Condition, out var tuple))
{
var body = member.Ignore.IsChildPath
? member.Ignore.Condition.Body
: member.Ignore.Condition.Apply(arg.MapType, source, destination);
tuple = Tuple.Create(new List<Expression>(), body);
conditions[member.Ignore.Condition] = tuple;
}
tuple.Item1.Add(adapt);
}
else
lines.Add(adapt);
}
if (conditions != null)
{
foreach (var kvp in conditions)
{
var condition = Expression.IfThen(
ExpressionEx.Not(kvp.Value.Item2),
Expression.Block(kvp.Value.Item1));
lines.Add(condition);
}
}
return lines.Count > 0 ? (Expression)Expression.Block(lines) : Expression.Empty();
}
private static Expression SetValueByReflection(MemberMapping member, MemberExpression adapt)
{
var typeofExpression = Expression.Constant(member.Destination!.Type);
var getPropertyMethod = typeof(Type).GetMethod("GetProperty", new[] { typeof(string), typeof(Type) })!;
var getPropertyExpression = Expression.Call(typeofExpression, getPropertyMethod,
new[] { Expression.Constant(member.DestinationMember.Name), Expression.Constant(member.DestinationMember.Type) });
var setValueMethod =
typeof(PropertyInfo).GetMethod("SetValue", new[] { typeof(object), typeof(object) })!;
var memberAsObject = adapt.To(typeof(object));
return Expression.Call(getPropertyExpression, setValueMethod,
new[] { member.Destination, memberAsObject });
}
protected override Expression? CreateInlineExpression(Expression source, CompileArgument arg, bool IsRequiredOnly = false)
{
//new TDestination {
// Prop1 = convert(src.Prop1),
// Prop2 = convert(src.Prop2),
//}
var exp = CreateInstantiationExpression(source, arg);
var memberInit = exp as MemberInitExpression;
var newInstance = memberInit?.NewExpression ?? (NewExpression)exp;
var contructorMembers = newInstance.GetAllMemberExpressionsMemberInfo().ToArray();
ClassModel? classModel;
ClassMapping? classConverter;
if (IsRequiredOnly)
{
classModel = GetOnlyRequiredPropertySetterModel(arg);
classConverter = CreateClassConverter(source, classModel, arg, ctorMapping: true);
}
else
{
classModel = GetSetterModel(arg);
classConverter = CreateClassConverter(source, classModel, arg);
}
var members = classConverter.Members;
var lines = new List<MemberBinding>();
if (memberInit != null)
lines.AddRange(memberInit.Bindings);
foreach (var member in members)
{
if (member.UseDestinationValue)
return null;
if (!arg.Settings.Resolvers.Any(r => r.DestinationMemberName == member.DestinationMember.Name)
&& member.Getter is MemberExpression memberExp && contructorMembers.Contains(memberExp.Member))
continue;
if (member.DestinationMember.SetterModifier == AccessModifier.None)
continue;
Expression value;
// convert ApplyNullable Propagation for NotPrimitive Nullable types
if (member.Getter is ConditionalExpression cond && member.Getter.Type.IsNotPrimitiveNullableType()
&& !member.DestinationMember.Type.IsNullable())
{
var adapt = CreateAdaptExpression(cond.IfTrue.GetNotPrimitiveNullableValue(), member.DestinationMember.Type, arg, member);
value = Expression.Condition(cond.Test, adapt, member.DestinationMember.Type.CreateDefault());
}
else
value = CreateAdaptExpression(member.Getter, member.DestinationMember.Type, arg, member);
//special null property check for projection
//if we don't set null to property, EF will create empty object
//except collection type & complex type which cannot be null
if (arg.MapType == MapType.Projection
&& member.Getter.Type != member.DestinationMember.Type
&& !member.Getter.Type.IsCollection()
&& !member.DestinationMember.Type.IsCollection()
&& member.Getter.Type.GetTypeInfo().GetCustomAttributesData().All(attr => attr.GetAttributeType().Name != "ComplexTypeAttribute"))
{
value = member.Getter.NotNullReturn(value);
}
var bind = Expression.Bind((MemberInfo)member.DestinationMember.Info!, value);
lines.Add(bind);
}
return Expression.MemberInit(newInstance, lines);
}
}
}