-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathautomapper_expression_api.linq
More file actions
67 lines (51 loc) · 1.39 KB
/
automapper_expression_api.linq
File metadata and controls
67 lines (51 loc) · 1.39 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
<Query Kind="Program" />
void Main()
{
Expression<Func<A, B>> exp = a => new B { Id = a.Id, Name = a.Name };
Mapper.To<B>(new A { Id = 2, Name = "Something asdf" }).Dump("result");
}
public class Mapper
{
public static Dictionary<(Type, Type), Delegate> _cache = new ();
public static T To<T>(object o)
{
var inType = o.GetType();
var outType = typeof(T);
var key= (inType, outType);
if(!_cache.ContainsKey(key)){
_cache[key] = CreateDelegate(inType, outType);
}
return (T) _cache[key].DynamicInvoke(o);
}
private static Delegate CreateDelegate(Type inType, Type outType)
{
var param = Expression.Parameter(inType);
var newExpression = Expression.New(outType.GetConstructor(Type.EmptyTypes));
List<MemberBinding> bindings = new();
foreach (var prop in inType.GetProperties())
{
var tbm = outType.GetProperty(prop.Name);
if (tbm == null)
{
continue;
}
var pma = Expression.MakeMemberAccess(param, prop);
var binding = Expression.Bind(tbm, pma);
bindings.Add(binding);
}
var body = Expression.MemberInit(newExpression, bindings);
return Expression.Lambda(body, false, param).Compile();
}
}
public class A
{
public int Id { get; set; }
public string Name { get; set; }
public string Body { get; set; } = "asdfasdfasdfdsa";
}
public class B
{
public int Id { get; set; }
public string Name { get; set; }
public string Body { get; set; }
}