Repository navigation
Expand file tree
/
Copy pathObjectContextBase.SaveChanges.cs
More file actions
358 lines (298 loc) · 10.3 KB
/
Copy pathObjectContextBase.SaveChanges.cs
File metadata and controls
358 lines (298 loc) · 10.3 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
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Data.Entity.Infrastructure;
using System.Data.Entity.Validation;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using SmartStore.Core;
using SmartStore.Core.Data.Hooks;
using SmartStore.Utilities;
using SmartStore.Utilities.ObjectPools;
using EfState = System.Data.Entity.EntityState;
namespace SmartStore.Data
{
public abstract partial class ObjectContextBase
{
private SaveChangesOperation _currentSaveOperation;
private readonly static ConcurrentDictionary<Type, bool> _hookableEntities = new ConcurrentDictionary<Type, bool>();
private enum SaveStage
{
PreSave,
PostSave
}
private IEnumerable<DbEntityEntry> GetChangedEntries()
{
return ChangeTracker.Entries().Where(x => x.State > EfState.Unchanged);
}
public IDbHookHandler DbHookHandler
{
get;
set;
}
public override int SaveChanges()
{
var op = _currentSaveOperation;
if (op != null)
{
if (op.Stage == SaveStage.PreSave)
{
// This was called from within a PRE action hook. We must get out:...
// 1.) to prevent cyclic calls
// 2.) we want new entities in the state tracker (added by pre hooks) to be committed atomically in the core SaveChanges() call later on.
return 0;
}
else if (op.Stage == SaveStage.PostSave)
{
// This was called from within a POST action hook. Core SaveChanges() has already been called,
// but new entities could have been added to the state tracker by hooks.
// Therefore we need to commit them and get outta here, otherwise: cyclic nightmare!
// DetectChanges() here is important, 'cause we turned it off for the save process.
base.ChangeTracker.DetectChanges();
return SaveChangesCore();
}
}
_currentSaveOperation = new SaveChangesOperation(this, this.DbHookHandler);
Action endExecute = () =>
{
_currentSaveOperation?.Dispose();
_currentSaveOperation = null;
};
using (new ActionDisposable(endExecute))
{
return _currentSaveOperation.Execute();
}
}
public override Task<int> SaveChangesAsync(CancellationToken cancellationToken)
{
var op = _currentSaveOperation;
if (op != null)
{
if (op.Stage == SaveStage.PreSave)
{
// This was called from within a PRE action hook. We must get out:...
// 1.) to prevent cyclic calls
// 2.) we want new entities in the state tracker (added by pre hooks) to be committed atomically in the core SaveChanges() call later on.
return Task.FromResult(0);
}
else if (op.Stage == SaveStage.PostSave)
{
// This was called from within a POST action hook. Core SaveChanges() has already been called,
// but new entities could have been added to the state tracker by hooks.
// Therefore we need to commit them and get outta here, otherwise: cyclic nightmare!
// DetectChanges() here is important, 'cause we turned it off for the save process.
base.ChangeTracker.DetectChanges();
return SaveChangesCoreAsync(cancellationToken);
}
}
_currentSaveOperation = new SaveChangesOperation(this, this.DbHookHandler);
var result = _currentSaveOperation.ExecuteAsync(cancellationToken);
result.ContinueWith(t =>
{
_currentSaveOperation?.Dispose();
_currentSaveOperation = null;
});
return result;
}
/// <summary>
/// Just calls <c>DbContext.SaveChanges()</c> without any sugar
/// </summary>
/// <returns>The number of affected records</returns>
protected internal int SaveChangesCore()
{
return base.SaveChanges();
}
/// <summary>
/// Just calls <c>DbContext.SaveChangesAsync()</c> without any sugar
/// </summary>
/// <returns>The number of affected records</returns>
protected internal Task<int> SaveChangesCoreAsync(CancellationToken cancellationToken)
{
return base.SaveChangesAsync(cancellationToken);
}
private void IgnoreMergedData(IEnumerable<IMergedData> entries, bool ignore)
{
foreach (var entry in entries)
{
entry.MergedDataIgnore = ignore;
}
}
internal bool IsInSaveOperation
{
get { return _currentSaveOperation != null; }
}
private bool IsHookableEntry(IHookedEntity entry)
{
var entity = entry.Entity;
if (entity == null)
{
return false;
}
return IsHookableEntityType(entry.EntityType);
}
private static bool IsHookableEntityType(Type entityType)
{
var isHookable = _hookableEntities.GetOrAdd(entityType, t =>
{
var attr = t.GetAttribute<HookableAttribute>(true);
if (attr != null)
{
return attr.IsHookable;
}
// Entities are hookable by default
return true;
});
return isHookable;
}
class SaveChangesOperation : IDisposable
{
private SaveStage _stage;
private IEnumerable<DbEntityEntry> _changedEntries;
private ObjectContextBase _ctx;
private IDbHookHandler _hookHandler;
public SaveChangesOperation(ObjectContextBase ctx, IDbHookHandler hookHandler)
{
_ctx = ctx;
_hookHandler = hookHandler;
}
public IEnumerable<DbEntityEntry> ChangedEntries
{
get { return _changedEntries; }
}
public SaveStage Stage
{
get { return _stage; }
}
private IDisposable ExecuteCore()
{
var autoDetectChanges = _ctx.Configuration.AutoDetectChangesEnabled;
IEnumerable<IMergedData> mergeableEntities = null;
// Suppress implicit DetectChanges() calls by EF,
// e.g. called by SaveChanges(), ChangeTracker.Entries() etc.
_ctx.Configuration.AutoDetectChangesEnabled = false;
// Get all attached entries implementing IMergedData,
// we need to ignore merge on them. Otherwise
// EF's change detection may think that properties has changed
// where they actually didn't.
mergeableEntities = _ctx.GetMergeableEntitiesFromChangeTracker().ToArray();
// Now ignore merged data, otherwise merged data will be saved to database
_ctx.IgnoreMergedData(mergeableEntities, true);
// We must detect changes earlier in the process
// before hooks are executed. Therefore we suppressed the
// implicit DetectChanges() call by EF and call it here explicitly.
_ctx.ChangeTracker.DetectChanges();
// Now get changed entries
_changedEntries = _ctx.GetChangedEntries();
// pre
PreExecute(out IEnumerable<IHookedEntity> changedHookEntries);
return new ActionDisposable(endExecute);
void endExecute()
{
try
{
// post
PostExecute(changedHookEntries);
}
finally
{
_ctx.Configuration.AutoDetectChangesEnabled = autoDetectChanges;
_ctx.IgnoreMergedData(mergeableEntities, false);
}
}
}
public int Execute()
{
using (ExecuteCore())
{
return _ctx.SaveChangesCore();
}
}
public async Task<int> ExecuteAsync(CancellationToken cancellationToken)
{
using (ExecuteCore())
{
return await _ctx.SaveChangesCoreAsync(cancellationToken);
}
}
private IEnumerable<IDbSaveHook> PreExecute(out IEnumerable<IHookedEntity> changedHookEntries)
{
bool enableHooks = false;
bool importantHooksOnly = false;
bool anyStateChanged = false;
IEnumerable<IDbSaveHook> processedHooks = null;
changedHookEntries = null;
enableHooks = _changedEntries.Any(); // hooking is meaningless without hookable entries
if (enableHooks)
{
// despite the fact that hooking can be disabled, we MUST determine if any "important" pre hook exists.
// If yes, but hooking is disabled, we'll trigger only the important ones.
importantHooksOnly = !_ctx.HooksEnabled && _hookHandler.HasImportantSaveHooks();
// we'll enable hooking for this unit of work only when it's generally enabled,
// OR we have "important" hooks in the pipeline.
enableHooks = importantHooksOnly || _ctx.HooksEnabled;
}
if (enableHooks)
{
changedHookEntries = _changedEntries
.Select(x => new HookedEntity(x))
.Where(x => IsHookableEntityType(x.EntityType))
.ToArray();
// Regardless of validation (possible fixing validation errors too)
processedHooks = _hookHandler.TriggerPreSaveHooks(changedHookEntries, importantHooksOnly, out anyStateChanged);
if (processedHooks.Any() && changedHookEntries.Any(x => x.State == SmartStore.Core.Data.EntityState.Modified))
{
// Because at least one pre action hook has been processed,
// we must assume that entity properties has been changed.
// We need to call DetectChanges() again.
_ctx.ChangeTracker.DetectChanges();
}
}
if (anyStateChanged)
{
// because the state of at least one entity has been changed during pre hooking
// we have to further reduce the set of hookable entities (for the POST hooks)
changedHookEntries = changedHookEntries.Where(x => x.InitialState > SmartStore.Core.Data.EntityState.Unchanged);
}
return processedHooks ?? Enumerable.Empty<IDbSaveHook>();
}
private IEnumerable<IDbSaveHook> PostExecute(IEnumerable<IHookedEntity> changedHookEntries)
{
if (changedHookEntries == null || !changedHookEntries.Any())
return Enumerable.Empty<IDbSaveHook>();
// the existence of hook entries actually implies that hooking is enabled.
_stage = SaveStage.PostSave;
var importantHooksOnly = !_ctx.HooksEnabled && _hookHandler.HasImportantSaveHooks();
return _hookHandler.TriggerPostSaveHooks(changedHookEntries, importantHooksOnly);
}
private string FormatValidationExceptionMessage(IEnumerable<DbEntityValidationResult> results)
{
var psb = PooledStringBuilder.Rent();
var sb = (StringBuilder)psb;
sb.Append("Entity validation failed" + Environment.NewLine);
foreach (var res in results)
{
var baseEntity = res.Entry.Entity as BaseEntity;
sb.AppendFormat("Entity Name: {0} - Id: {0} - State: {1}",
res.Entry.Entity.GetType().Name,
baseEntity != null ? baseEntity.Id.ToString() : "N/A",
res.Entry.State.ToString());
sb.AppendLine();
foreach (var validationError in res.ValidationErrors)
{
sb.AppendFormat("\tProperty: {0} Error: {1}", validationError.PropertyName, validationError.ErrorMessage);
sb.AppendLine();
}
}
return psb.ToStringAndReturn();
}
public void Dispose()
{
_ctx = null;
_hookHandler = null;
_changedEntries = null;
}
}
}
}