-
Notifications
You must be signed in to change notification settings - Fork 74
/
ChangeTracker.cs
47 lines (45 loc) · 1.92 KB
/
ChangeTracker.cs
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
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using KellermanSoftware.CompareNetObjects;
namespace Repository.ChangeTracking
{
internal class ChangeTracker<T>
{
//===============================================================
static ChangeTracker()
{
CanTrackChanges = typeof(T).GetConstructor(Type.EmptyTypes) != null;
}
//===============================================================
public ChangeTracker(T value, Func<T, object[]> keySelector)
{
CurrentValue = value;
KeySelector = keySelector;
InitialValue = CanTrackChanges ? (T)Activator.CreateInstance(typeof(T)) : default(T);
if (CanTrackChanges)
AutoMapper.Mapper.DynamicMap(CurrentValue, InitialValue);
}
//===============================================================
public static bool CanTrackChanges { get; private set; }
//===============================================================
public Func<T, Object[]> KeySelector { get; private set; }
//===============================================================
public T CurrentValue { get; private set; }
//===============================================================
public T InitialValue { get; private set; }
//===============================================================
internal bool HasChanges
{
get
{
if (!KeySelector(CurrentValue).SequenceEqual(KeySelector(InitialValue)))
throw new InvalidOperationException("You cannot change an object's key value.");
return CanTrackChanges && !new CompareObjects().Compare(CurrentValue, InitialValue);
}
}
//===============================================================
}
}