-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathObjectMapperBase.cs
More file actions
73 lines (65 loc) · 2 KB
/
Copy pathObjectMapperBase.cs
File metadata and controls
73 lines (65 loc) · 2 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
using DataKit.Modelling.TypeModels;
using System.Collections.Generic;
namespace DataKit.Mapping
{
public abstract class ObjectMapperBase : IObjectMapper
{
protected readonly IObjectFactory objectFactory;
protected ObjectMapperBase(IObjectFactory objectFactory)
{
this.objectFactory = objectFactory;
}
protected abstract Mapping<TypeModel<TFrom>, PropertyField, TypeModel<TTo>, PropertyField> GetMapping<TFrom, TTo>()
where TFrom : class
where TTo : class;
public void Inject<TFrom, TTo>(TFrom from, TTo to)
where TFrom : class
where TTo : class
{
InjectSingle(from, to, GetMapping<TFrom, TTo>());
}
protected virtual void InjectSingle<TFrom, TTo>(TFrom from, TTo to,
Mapping<TypeModel<TFrom>, PropertyField, TypeModel<TTo>, PropertyField> mapping)
where TFrom : class
where TTo : class
{
var reader = new ObjectDataModelReader<TFrom>(from);
var writer = new ObjectDataModelWriter<TTo>(to, objectFactory);
mapping.Run(reader, writer);
}
public void InjectAll<TFrom, TTo>(IEnumerable<TFrom> from, IEnumerable<TTo> to)
where TFrom : class
where TTo : class
{
var mapping = GetMapping<TFrom, TTo>();
using (var fromEnumerator = from.GetEnumerator())
using (var toEnumerator = to.GetEnumerator())
{
while (fromEnumerator.MoveNext() && toEnumerator.MoveNext())
{
InjectSingle(fromEnumerator.Current, toEnumerator.Current, mapping);
}
}
}
public TTo Map<TFrom, TTo>(TFrom from)
where TFrom : class
where TTo : class
{
var to = objectFactory.CreateInstance<TTo>();
InjectSingle(from, to, GetMapping<TFrom, TTo>());
return to;
}
public IEnumerable<TTo> MapAll<TFrom, TTo>(IEnumerable<TFrom> from)
where TFrom : class
where TTo : class
{
var mapping = GetMapping<TFrom, TTo>();
foreach (var obj in from)
{
var to = objectFactory.CreateInstance<TTo>();
InjectSingle(obj, to, mapping);
yield return to;
}
}
}
}