Repository navigation
Expand file tree
/
Copy pathObjectContextBase.SaveChanges.cs
More file actions
283 lines (237 loc) · 7.96 KB
/
Copy pathObjectContextBase.SaveChanges.cs
File metadata and controls
283 lines (237 loc) · 7.96 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
using System;
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 System.Web.Hosting;
using SmartStore.Core;
using SmartStore.Core.Data.Hooks;
using SmartStore.Core.Infrastructure;
using SmartStore.Utilities;
namespace SmartStore.Data
{
public abstract partial class ObjectContextBase
{
private IDbHookHandler _dbHookHandler;
private SaveChangesOperation _currentSaveOperation;
enum SaveStage
{
PreSave,
PostSave
}
private IEnumerable<DbEntityEntry> GetChangedEntries()
{
return ChangeTracker.Entries().Where(x => x.State > System.Data.Entity.EntityState.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!
return SaveChangesCore();
}
}
_currentSaveOperation = new SaveChangesOperation(this, this.DbHookHandler);
using (new ActionDisposable(() => _currentSaveOperation = null))
{
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!
return SaveChangesCoreAsync(cancellationToken);
}
}
_currentSaveOperation = new SaveChangesOperation(this, this.DbHookHandler);
using (new ActionDisposable(() => _currentSaveOperation = null))
{
return _currentSaveOperation.ExecuteAsync(cancellationToken);
}
}
/// <summary>
/// Just calls <c>DbContext.SaveChanges()</c> without any sugar
/// </summary>
/// <returns>The number of affected records</returns>
protected internal int SaveChangesCore()
{
var changedEntries = _currentSaveOperation?.ChangedEntries ?? GetChangedEntries();
using (new ActionDisposable(() => IgnoreMergedData(changedEntries, false)))
{
IgnoreMergedData(changedEntries, true);
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)
{
var changedEntries = _currentSaveOperation?.ChangedEntries ?? GetChangedEntries();
using (new ActionDisposable(() => IgnoreMergedData(changedEntries, false)))
{
IgnoreMergedData(changedEntries, true);
return base.SaveChangesAsync(cancellationToken);
}
}
private void IgnoreMergedData(IEnumerable<DbEntityEntry> entries, bool ignore)
{
foreach (var entry in entries.Select(x => x.Entity).OfType<IMergedData>())
{
entry.MergedDataIgnore = ignore;
}
}
class SaveChangesOperation : IDisposable
{
private SaveStage _stage;
private IList<DbEntityEntry> _changedEntries;
private ObjectContextBase _ctx;
private IDbHookHandler _hookHandler;
public SaveChangesOperation(ObjectContextBase ctx, IDbHookHandler hookHandler)
{
_ctx = ctx;
_hookHandler = hookHandler;
_changedEntries = ctx.GetChangedEntries().ToList();
}
public IEnumerable<DbEntityEntry> ChangedEntries
{
get { return _changedEntries; }
}
public SaveStage Stage
{
get { return _stage; }
}
public int Execute()
{
// pre
HookedEntity[] changedHookEntries;
PreExecute(out changedHookEntries);
// save
var result = _ctx.SaveChangesCore();
// post
PostExecute(changedHookEntries);
return result;
}
public Task<int> ExecuteAsync(CancellationToken cancellationToken)
{
// pre
HookedEntity[] changedHookEntries;
PreExecute(out changedHookEntries);
// save
var result = _ctx.SaveChangesCoreAsync(cancellationToken);
// post
result.ContinueWith((t) =>
{
if (!t.IsFaulted)
{
PostExecute(changedHookEntries);
}
});
return result;
}
private void PreExecute(out HookedEntity[] changedHookEntries)
{
bool enableHooks = false;
bool importantHooksOnly = false;
bool anyStateChanged = false;
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))
.ToArray();
// Regardless of validation (possible fixing validation errors too)
anyStateChanged = _hookHandler.TriggerPreSaveHooks(changedHookEntries, importantHooksOnly);
}
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)
.ToArray();
}
}
private void PostExecute(HookedEntity[] changedHookEntries)
{
if (changedHookEntries == null || changedHookEntries.Length == 0)
return;
// the existence of hook entries actually implies that hooking is enabled.
_stage = SaveStage.PostSave;
var importantHooksOnly = !_ctx.HooksEnabled && _hookHandler.HasImportantSaveHooks();
_hookHandler.TriggerPostSaveHooks(changedHookEntries, importantHooksOnly);
}
private string FormatValidationExceptionMessage(IEnumerable<DbEntityValidationResult> results)
{
var sb = new StringBuilder();
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 sb.ToString();
}
public void Dispose()
{
_ctx = null;
_hookHandler = null;
_changedEntries = null;
}
}
}
}