forked from smartstore/SmartStoreNET
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathObjectContextBase.cs
More file actions
687 lines (578 loc) · 19.4 KB
/
Copy pathObjectContextBase.cs
File metadata and controls
687 lines (578 loc) · 19.4 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
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Common;
using System.Data.SqlClient;
using System.Data.Entity;
using System.Data.Entity.Infrastructure;
using System.Data.Entity.Validation;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
using SmartStore.Core;
using SmartStore.Core.Data;
using SmartStore.Core.Data.Hooks;
using Microsoft.SqlServer;
using Microsoft.SqlServer.Management.Common;
using Microsoft.SqlServer.Management.Smo;
using SmartStore.Core.Infrastructure;
using SmartStore.Core.Events;
namespace SmartStore.Data
{
/// <summary>
/// Object context
/// </summary>
[DbConfigurationType(typeof(SmartDbConfiguration))]
public abstract class ObjectContextBase : DbContext, IDbContext
{
private static bool? s_isSqlServer2012OrHigher = null;
#region Ctor
/// <summary>
/// Parameterless constructor for tooling support, e.g. EF Migrations.
/// </summary>
protected ObjectContextBase()
: this(GetConnectionString(), null)
{
}
protected ObjectContextBase(string nameOrConnectionString, string alias = null)
: base(nameOrConnectionString)
{
this.HooksEnabled = true;
this.Alias = null;
this.EventPublisher = NullEventPublisher.Instance;
}
#endregion
#region Properties
public IEventPublisher EventPublisher
{
get;
set;
}
#endregion
#region Hooks
private readonly IList<DbEntityEntry> _hookedEntries = new List<DbEntityEntry>();
private void PerformPreSaveActions(out IList<DbEntityEntry> modifiedEntries, out HookedEntityEntry[] modifiedHookEntries)
{
modifiedHookEntries = null;
modifiedEntries = this.ChangeTracker.Entries()
.Where(x => x.State != System.Data.Entity.EntityState.Unchanged && x.State != System.Data.Entity.EntityState.Detached)
.Except(_hookedEntries)
.ToList();
// prevents stack overflow
_hookedEntries.AddRange(modifiedEntries);
var hooksEnabled = this.HooksEnabled && modifiedEntries.Any();
if (hooksEnabled)
{
modifiedHookEntries = modifiedEntries
.Select(x => new HookedEntityEntry()
{
Entity = x.Entity,
PreSaveState = (SmartStore.Core.Data.EntityState)((int)x.State)
})
.ToArray();
// Regardless of validation (possible fixing validation errors too)
this.EventPublisher.Publish(new PreActionHookEvent { ModifiedEntries = modifiedHookEntries, RequiresValidation = false });
}
if (this.Configuration.ValidateOnSaveEnabled)
{
var results = from entry in this.ChangeTracker.Entries()
where this.ShouldValidateEntity(entry)
let validationResult = entry.GetValidationResult()
where !validationResult.IsValid
select validationResult;
if (results.Any())
{
var fail = new DbEntityValidationException(FormatValidationExceptionMessage(results), results);
//Debug.WriteLine(fail.Message, fail);
throw fail;
}
}
if (hooksEnabled)
{
this.EventPublisher.Publish(new PreActionHookEvent { ModifiedEntries = modifiedHookEntries, RequiresValidation = true });
}
modifiedEntries.Each(x => _hookedEntries.Remove(x));
IgnoreMergedData(modifiedEntries, true);
}
private void PerformPostSaveActions(IList<DbEntityEntry> modifiedEntries, HookedEntityEntry[] modifiedHookEntries)
{
IgnoreMergedData(modifiedEntries, false);
if (this.HooksEnabled && modifiedHookEntries != null && modifiedHookEntries.Any())
{
this.EventPublisher.Publish(new PostActionHookEvent { ModifiedEntries = modifiedHookEntries });
}
}
public bool HooksEnabled
{
get;
set;
}
#endregion
#region IDbContext members
public virtual string CreateDatabaseScript()
{
return ((IObjectContextAdapter)this).ObjectContext.CreateDatabaseScript();
}
public new DbSet<TEntity> Set<TEntity>() where TEntity : BaseEntity
{
return base.Set<TEntity>();
}
private IEnumerable<DbParameter> ToParameters(params object[] parameters)
{
if (parameters == null || parameters.Length == 0)
return Enumerable.Empty<DbParameter>();
return parameters.Cast<DbParameter>();
}
public virtual IList<TEntity> ExecuteStoredProcedureList<TEntity>(string commandText, params object[] parameters) where TEntity : BaseEntity, new()
{
// Add parameters to command
var commandText2 = commandText;
var dbParams = ToParameters(parameters);
bool firstParam = true;
bool hasOutputParams = false;
foreach (var p in dbParams)
{
commandText += firstParam ? " " : ", ";
firstParam = false;
commandText += "@" + p.ParameterName;
if (p.Direction == ParameterDirection.InputOutput || p.Direction == ParameterDirection.Output)
{
// output parameter
hasOutputParams = true;
commandText += " output";
}
}
var isLegacyDb = !this.IsSqlServer2012OrHigher();
if (isLegacyDb && hasOutputParams)
{
// SQL Server 2008 or lower is not capable of handling
// stored procedures with output parameters
return ExecuteStoredProcedureListLegacy<TEntity>(commandText2, dbParams);
}
var result = this.Database.SqlQuery<TEntity>(commandText, parameters).ToList();
if (!ForceNoTracking)
{
using (var scope = new DbContextScope(this, autoDetectChanges: false))
{
for (int i = 0; i < result.Count; i++)
{
result[i] = AttachEntityToContext(result[i]);
}
}
}
return result;
}
private IList<TEntity> ExecuteStoredProcedureListLegacy<TEntity>(string commandText, IEnumerable<DbParameter> parameters) where TEntity : BaseEntity, new()
{
var connection = this.Database.Connection;
// Don't close the connection after command execution
// open the connection for use
if (connection.State == ConnectionState.Closed)
connection.Open();
// create a command object
using (var cmd = connection.CreateCommand())
{
// command to execute
cmd.CommandText = commandText;
cmd.CommandType = CommandType.StoredProcedure;
// move parameters to command object
cmd.Parameters.AddRange(parameters.ToArray());
// database call
var reader = cmd.ExecuteReader();
var result = ((IObjectContextAdapter)(this)).ObjectContext.Translate<TEntity>(reader).ToList();
if (!ForceNoTracking)
{
for (int i = 0; i < result.Count; i++)
{
result[i] = AttachEntityToContext(result[i]);
}
}
// close up the reader, we're done saving results
reader.Close();
return result;
}
}
/// <summary>
/// Creates a raw SQL query that will return elements of the given generic type.
/// The type can be any type that has properties that match the names of the columns returned from the query,
/// or can be a simple primitive type. The type does not have to be an entity type.
/// The results of this query are never tracked by the context even if the type of object returned is an entity type.
/// </summary>
/// <typeparam name="TElement">The type of object returned by the query.</typeparam>
/// <param name="sql">The SQL query string.</param>
/// <param name="parameters">The parameters to apply to the SQL query string.</param>
/// <returns>Result</returns>
public IEnumerable<TElement> SqlQuery<TElement>(string sql, params object[] parameters)
{
return this.Database.SqlQuery<TElement>(sql, parameters);
}
/// <summary>
/// Executes the given DDL/DML command against the database.
/// </summary>
/// <param name="sql">The command string</param>
/// <param name="timeout">Timeout value, in seconds. A null value indicates that the default value of the underlying provider will be used</param>
/// <param name="parameters">The parameters to apply to the command string.</param>
/// <returns>The result returned by the database after executing the command.</returns>
public int ExecuteSqlCommand(string sql, bool doNotEnsureTransaction = false, int? timeout = null, params object[] parameters)
{
Guard.ArgumentNotEmpty(sql, "sql");
int? previousTimeout = null;
if (timeout.HasValue)
{
//store previous timeout
previousTimeout = ((IObjectContextAdapter)this).ObjectContext.CommandTimeout;
((IObjectContextAdapter)this).ObjectContext.CommandTimeout = timeout;
}
var transactionalBehavior = doNotEnsureTransaction
? TransactionalBehavior.DoNotEnsureTransaction
: TransactionalBehavior.EnsureTransaction;
var result = this.Database.ExecuteSqlCommand(transactionalBehavior, sql, parameters);
if (timeout.HasValue)
{
//Set previous timeout back
((IObjectContextAdapter)this).ObjectContext.CommandTimeout = previousTimeout;
}
return result;
}
/// <summary>Executes sql by using SQL-Server Management Objects which supports GO statements.</summary>
public int ExecuteSqlThroughSmo(string sql)
{
Guard.ArgumentNotEmpty(sql, "sql");
int result = 0;
try
{
bool isSqlServer = DataSettings.Current.IsSqlServer;
if (!isSqlServer)
{
result = ExecuteSqlCommand(sql);
}
else
{
using (var sqlConnection = new SqlConnection(GetConnectionString()))
{
var serverConnection = new ServerConnection(sqlConnection);
var server = new Server(serverConnection);
result = server.ConnectionContext.ExecuteNonQuery(sql);
}
}
}
catch (Exception)
{
// remove the GO statements
sql = Regex.Replace(sql, @"\r{0,1}\n[Gg][Oo]\r{0,1}\n", "\n");
result = ExecuteSqlCommand(sql);
}
return result;
}
public bool HasChanges
{
get
{
return this.ChangeTracker.Entries()
.Where(x => x.State != System.Data.Entity.EntityState.Unchanged && x.State != System.Data.Entity.EntityState.Detached)
.Any();
}
}
public IDictionary<string, object> GetModifiedProperties(BaseEntity entity)
{
var props = new Dictionary<string, object>();
var entry = this.Entry(entity);
var modifiedPropertyNames = from p in entry.CurrentValues.PropertyNames
where entry.Property(p).IsModified
select p;
foreach (var name in modifiedPropertyNames)
{
props.Add(name, entry.Property(name).OriginalValue);
}
return props;
}
public override int SaveChanges()
{
IList<DbEntityEntry> modifiedEntries;
HookedEntityEntry[] modifiedHookEntries;
PerformPreSaveActions(out modifiedEntries, out modifiedHookEntries);
// SAVE NOW!!!
bool validateOnSaveEnabled = this.Configuration.ValidateOnSaveEnabled;
this.Configuration.ValidateOnSaveEnabled = false;
int result = this.Commit();
this.Configuration.ValidateOnSaveEnabled = validateOnSaveEnabled;
PerformPostSaveActions(modifiedEntries, modifiedHookEntries);
return result;
}
public override Task<int> SaveChangesAsync()
{
IList<DbEntityEntry> modifiedEntries;
HookedEntityEntry[] modifiedHookEntries;
PerformPreSaveActions(out modifiedEntries, out modifiedHookEntries);
// SAVE NOW!!!
bool validateOnSaveEnabled = this.Configuration.ValidateOnSaveEnabled;
this.Configuration.ValidateOnSaveEnabled = false;
var result = this.CommitAsync();
result.ContinueWith((t) =>
{
this.Configuration.ValidateOnSaveEnabled = validateOnSaveEnabled;
PerformPostSaveActions(modifiedEntries, modifiedHookEntries);
});
return result;
}
// codehint: sm-add (required for UoW implementation)
public string Alias { get; internal set; }
// performance on bulk inserts
public bool AutoDetectChangesEnabled
{
get
{
return this.Configuration.AutoDetectChangesEnabled;
}
set
{
this.Configuration.AutoDetectChangesEnabled = value;
}
}
// performance on bulk inserts
public bool ValidateOnSaveEnabled
{
get
{
return this.Configuration.ValidateOnSaveEnabled;
}
set
{
this.Configuration.ValidateOnSaveEnabled = value;
}
}
public bool ProxyCreationEnabled
{
get
{
return this.Configuration.ProxyCreationEnabled;
}
set
{
this.Configuration.ProxyCreationEnabled = value;
}
}
public bool ForceNoTracking { get; set; }
public ITransaction BeginTransaction(IsolationLevel isolationLevel = IsolationLevel.Unspecified)
{
var dbContextTransaction = this.Database.BeginTransaction(isolationLevel);
return new DbContextTransactionWrapper(dbContextTransaction);
}
public void UseTransaction(DbTransaction transaction)
{
this.Database.UseTransaction(transaction);
}
#endregion
#region Utils
/// <summary>
/// Resolves the connection string from the <c>Settings.txt</c> file
/// </summary>
/// <returns>The connection string</returns>
/// <remarks>This helper is called from parameterless DbContext constructors which are required for EF tooling support.</remarks>
public static string GetConnectionString()
{
if (DataSettings.Current.IsValid())
{
return DataSettings.Current.DataConnectionString;
}
throw Error.Application("A connection string could not be resolved for the parameterless constructor of the derived DbContext. Either the database is not installed, or the file 'Settings.txt' does not exist or contains invalid content.");
}
protected internal bool IsSqlServer2012OrHigher()
{
if (!s_isSqlServer2012OrHigher.HasValue)
{
try
{
// TODO: actually we should cache this value by connection (string).
// But fact is: it's quite unlikely that multiple DB versions are used within a single application scope.
var info = this.GetSqlServerInfo();
string productVersion = info.ProductVersion;
int version = productVersion.Split(new char[] { '.' })[0].ToInt();
s_isSqlServer2012OrHigher = version >= 11;
}
catch
{
s_isSqlServer2012OrHigher = false;
}
}
return s_isSqlServer2012OrHigher.Value;
}
/// <summary>
/// Attach an entity to the context or return an already attached entity (if it was already attached)
/// </summary>
/// <typeparam name="TEntity">TEntity</typeparam>
/// <param name="entity">Entity</param>
/// <returns>Attached entity</returns>
protected virtual TEntity AttachEntityToContext<TEntity>(TEntity entity) where TEntity : BaseEntity, new()
{
// little hack here until Entity Framework really supports stored procedures
// otherwise, navigation properties of loaded entities are not loaded until an entity is attached to the context
var alreadyAttached = Set<TEntity>().Local.Where(x => x.Id == entity.Id).FirstOrDefault();
if (alreadyAttached == null)
{
// attach new entity
Set<TEntity>().Attach(entity);
return entity;
}
else
{
// entity is already loaded.
return alreadyAttached;
}
}
public bool IsAttached<TEntity>(TEntity entity) where TEntity : BaseEntity, new()
{
Guard.ArgumentNotNull(() => entity);
return Set<TEntity>().Local.Where(x => x.Id == entity.Id).FirstOrDefault() != null;
}
public void DetachEntity<TEntity>(TEntity entity) where TEntity : BaseEntity, new()
{
Guard.ArgumentNotNull(() => entity);
if (this.IsAttached(entity))
{
((IObjectContextAdapter)this).ObjectContext.Detach(entity);
}
}
public void Detach(object entity)
{
((IObjectContextAdapter)this).ObjectContext.Detach(entity);
}
public int DetachAll()
{
var attachedEntities = this.ChangeTracker.Entries()
.Where(x => x.State != System.Data.Entity.EntityState.Detached)
.ToList();
attachedEntities.Each(x => this.Entry(x.Entity).State = System.Data.Entity.EntityState.Detached);
return attachedEntities.Count;
}
public void ChangeState<TEntity>(TEntity entity, System.Data.Entity.EntityState newState)
{
((IObjectContextAdapter)this).ObjectContext.ObjectStateManager.ChangeObjectState(entity, newState);
}
public bool SetToUnchanged<TEntity>(TEntity entity)
{
try
{
ChangeState<TEntity>(entity, System.Data.Entity.EntityState.Unchanged);
return true;
}
catch (Exception exc)
{
exc.Dump();
return false;
}
}
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();
}
private void IgnoreMergedData(IList<DbEntityEntry> entries, bool ignore)
{
try
{
foreach (var entry in entries)
{
var entityWithPossibleMergedData = entry.Entity as IMergedData;
if (entityWithPossibleMergedData != null)
entityWithPossibleMergedData.MergedDataIgnore = ignore;
}
}
catch { }
}
#endregion
#region EF helpers
private int Commit()
{
int result = 0;
bool commitFailed = false;
do
{
commitFailed = false;
try
{
result = base.SaveChanges();
}
catch (DbUpdateConcurrencyException ex)
{
commitFailed = true;
foreach (var entry in ex.Entries)
{
entry.Reload();
}
}
}
while (commitFailed);
return result;
}
private Task<int> CommitAsync()
{
var tcs = new TaskCompletionSource<int>();
base.SaveChangesAsync().ContinueWith((t) =>
{
if (!t.IsFaulted)
{
//if (t.IsCanceled)
//{
// tcs.TrySetCanceled();
// return;
//}
tcs.TrySetResult(t.Result);
return;
}
var ex = t.Exception.InnerException;
if (ex != null && ex is DbUpdateConcurrencyException)
{
// try again
tcs.TrySetResult(this.CommitAsync().Result);
}
else
{
tcs.TrySetException(ex);
}
});
return tcs.Task;
}
#endregion
#region Nested classes
private class DbContextTransactionWrapper : ITransaction
{
private readonly DbContextTransaction _tx;
public DbContextTransactionWrapper(DbContextTransaction tx)
{
Guard.ArgumentNotNull(() => tx);
_tx = tx;
}
public void Commit()
{
_tx.Commit();
}
public void Rollback()
{
_tx.Rollback();
}
public void Dispose()
{
_tx.Dispose();
}
}
#endregion
}
}