-
Notifications
You must be signed in to change notification settings - Fork 108
Expand file tree
/
Copy pathDbContextExtensions.cs
More file actions
218 lines (194 loc) · 9.2 KB
/
DbContextExtensions.cs
File metadata and controls
218 lines (194 loc) · 9.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
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
// Copyright (c) Arch team. All rights reserved.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.Json;
using Microsoft.EntityFrameworkCore.ChangeTracking;
using Microsoft.EntityFrameworkCore.Internal;
namespace Microsoft.EntityFrameworkCore
{
/// <summary>
/// Represents a plugin for Microsoft.EntityFrameworkCore to support automatically recording data changes history.
/// </summary>
public static class DbContextExtensions
{
/// <summary>
/// Ensures the automatic history.
/// </summary>
/// <param name="context">The context.</param>
public static void EnsureAutoHistory(this DbContext context)
{
EnsureAutoHistory<AutoHistory>(context, () => new AutoHistory());
}
public static void EnsureAutoHistory<TAutoHistory>(this DbContext context, Func<TAutoHistory> createHistoryFactory)
where TAutoHistory : AutoHistory
{
// Must ToArray() here for excluding the AutoHistory model.
// Currently, only support Modified and Deleted entity.
var entries = context.ChangeTracker.Entries().Where(e => e.State == EntityState.Modified || e.State == EntityState.Deleted).ToArray();
foreach (var entry in entries)
{
var autoHistory = entry.AutoHistory(createHistoryFactory);
if (autoHistory != null)
{
context.Add<TAutoHistory>(autoHistory);
}
}
}
internal static TAutoHistory AutoHistory<TAutoHistory>(this EntityEntry entry, Func<TAutoHistory> createHistoryFactory)
where TAutoHistory : AutoHistory
{
// Get not excluded mapped properties for the entity type.
// (include shadow properties, not include navigations & references)
var excludedProperties = entry.Metadata.ClrType.GetProperties()
.Where(p => p.GetCustomAttributes(typeof(ExcludeFromHistoryAttribute), true).Count() > 0)
.Select(p => p.Name);
var properties = entry.Properties.Where(f => !excludedProperties.Contains(f.Metadata.Name));
//Bug: If remaining properties to check are not modified, AutoHistory still returns an object with empty changes.
if (properties.Any(p => p.IsModified) || entry.State == EntityState.Deleted)
{
var history = createHistoryFactory();
history.TableName = entry.Metadata.GetTableName();
dynamic json = new System.Dynamic.ExpandoObject();
switch (entry.State)
{
case EntityState.Added:
foreach (var prop in properties)
{
if (prop.Metadata.IsKey() || prop.Metadata.IsForeignKey())
{
continue;
}
((IDictionary<String, Object>)json)[prop.Metadata.Name] = prop.CurrentValue;
}
// REVIEW: what's the best way to set the RowId?
history.RowId = "0";
history.Kind = EntityState.Added;
history.Changed = JsonSerializer.Serialize(json);
break;
case EntityState.Modified:
dynamic bef = new System.Dynamic.ExpandoObject();
dynamic aft = new System.Dynamic.ExpandoObject();
PropertyValues databaseValues = null;
foreach (var prop in properties)
{
if (prop.IsModified)
{
if (prop.OriginalValue != null)
{
if (!prop.OriginalValue.Equals(prop.CurrentValue))
{
((IDictionary<String, Object>)bef)[prop.Metadata.Name] = prop.OriginalValue;
}
else
{
databaseValues ??= entry.GetDatabaseValues();
var originalValue = databaseValues.GetValue<object>(prop.Metadata.Name);
((IDictionary<String, Object>)bef)[prop.Metadata.Name] = originalValue;
}
}
else
{
((IDictionary<String, Object>)bef)[prop.Metadata.Name] = null;
}
((IDictionary<String, Object>)aft)[prop.Metadata.Name] = prop.CurrentValue;
}
}
((IDictionary<String, Object>)json)["before"] = bef;
((IDictionary<String, Object>)json)["after"] = aft;
history.RowId = entry.PrimaryKey();
history.Kind = EntityState.Modified;
history.Changed = JsonSerializer.Serialize(json, AutoHistoryOptions.Instance.JsonSerializerOptions);
break;
case EntityState.Deleted:
foreach (var prop in properties)
{
((IDictionary<String, Object>)json)[prop.Metadata.Name] = prop.OriginalValue;
}
history.RowId = entry.PrimaryKey();
history.Kind = EntityState.Deleted;
history.Changed = JsonSerializer.Serialize(json, AutoHistoryOptions.Instance.JsonSerializerOptions);
break;
case EntityState.Detached:
case EntityState.Unchanged:
default:
throw new NotSupportedException("AutoHistory only support Deleted and Modified entity.");
}
return history;
}
else
{
return null;
}
}
/// <summary>
/// Ensures the history for added entries
/// </summary>
/// <param name="context"></param>
/// <param name="addedEntries"></param>
public static void EnsureAddedHistory(
this DbContext context,
EntityEntry[] addedEntries)
{
EnsureAddedHistory<AutoHistory>(
context,
() => new AutoHistory(),
addedEntries);
}
public static void EnsureAddedHistory<TAutoHistory>(
this DbContext context,
Func<TAutoHistory> createHistoryFactory,
EntityEntry[] addedEntries)
where TAutoHistory : AutoHistory
{
foreach (var entry in addedEntries)
{
var autoHistory = entry.AddedHistory(createHistoryFactory);
if (autoHistory != null)
{
context.Add<TAutoHistory>(autoHistory);
}
}
}
internal static TAutoHistory AddedHistory<TAutoHistory>(
this EntityEntry entry,
Func<TAutoHistory> createHistoryFactory)
where TAutoHistory : AutoHistory
{
var history = createHistoryFactory();
history.TableName = entry.Metadata
.GetTableName();
// Get the mapped properties for the entity type.
// (include shadow properties, not include navigations & references)
var excludedProperties = entry.Metadata.ClrType.GetProperties()
.Where(p => p.GetCustomAttributes(typeof(ExcludeFromHistoryAttribute), true).Count() > 0)
.Select(p => p.Name);
var properties = entry.Properties.Where(f => !excludedProperties.Contains(f.Metadata.Name));
dynamic json = new System.Dynamic.ExpandoObject();
foreach (var prop in properties)
{
((IDictionary<string, object>)json)[prop.Metadata.Name] = prop.OriginalValue != null ?
prop.OriginalValue
: null;
}
history.RowId = entry.PrimaryKey();
history.Kind = EntityState.Added;
history.Changed = JsonSerializer.Serialize(json, AutoHistoryOptions.Instance.JsonSerializerOptions);
return history;
}
private static string PrimaryKey(this EntityEntry entry)
{
var key = entry.Metadata.FindPrimaryKey();
var values = new List<object>();
foreach (var property in key.Properties)
{
var value = entry.Property(property.Name).CurrentValue;
if (value != null)
{
values.Add(value);
}
}
return string.Join(",", values);
}
}
}