forked from Trendyol/Trendyol.App
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathDataContextBase.cs
189 lines (156 loc) · 6.82 KB
/
DataContextBase.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
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
using System;
using System.Collections.Generic;
using System.Data.Common;
using System.Data.Entity;
using System.Data.Entity.Infrastructure;
using System.Data.Entity.Infrastructure.Interception;
using System.Linq;
using System.Reflection;
using System.Threading;
using System.Threading.Tasks;
using Common.Logging;
using EntityFramework.DynamicFilters;
using EntityFramework.InterceptorEx;
using Trendyol.App.Data;
using Trendyol.App.Data.Attributes;
using Trendyol.App.EntityFramework.Mapping;
namespace Trendyol.App.EntityFramework
{
public abstract class DataContextBase : DbContext
{
private static readonly ILog Logger = LogManager.GetLogger<DataContextBase>();
protected bool SetUpdatedOnSameAsCreatedOnForNewObjects { get; set; }
public DataContextBase(string connectionStringName, bool logExecutedQueries = false)
: base(connectionStringName)
{
InitializeContext(logExecutedQueries);
}
public DataContextBase(DbConnection existingConnection, bool contextOwnsConnection, bool logExecutedQueries = false)
: base(existingConnection, contextOwnsConnection)
{
InitializeContext(logExecutedQueries);
}
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
IEnumerable<Type> typesToRegister = GetType().Assembly.GetTypes()
.Where(type => !String.IsNullOrEmpty(type.Namespace))
.Where(
type =>
type.BaseType != null && type.BaseType.IsGenericType &&
type.BaseType.GetGenericTypeDefinition() == typeof(DataEntityTypeConfiguration<>));
foreach (var type in typesToRegister)
{
DataContextAttribute dataContextAttribute = type.GetCustomAttribute<DataContextAttribute>();
if (dataContextAttribute == null || dataContextAttribute.Type == GetType())
{
dynamic configurationInstance = Activator.CreateInstance(type);
modelBuilder.Configurations.Add(configurationInstance);
}
}
modelBuilder.Filter("SoftDeleteFilter", (ISoftDeletable d) => d.IsDeleted, false);
}
public override int SaveChanges()
{
HandleSoftDeletableEntities();
HandleAuditableEntities();
return base.SaveChanges();
}
public override Task<int> SaveChangesAsync()
{
HandleSoftDeletableEntities();
HandleAuditableEntities();
return base.SaveChangesAsync();
}
private void HandleSoftDeletableEntities()
{
IEnumerable<DbEntityEntry> entries = ChangeTracker.Entries().Where(x => x.Entity is ISoftDeletable && x.State == EntityState.Deleted);
foreach (var entry in entries)
{
entry.State = EntityState.Modified;
ISoftDeletable entity = (ISoftDeletable)entry.Entity;
entity.IsDeleted = true;
}
}
private void HandleAuditableEntities()
{
string currentUser = Thread.CurrentPrincipal?.Identity?.Name;
IEnumerable<DbEntityEntry> entities = ChangeTracker.Entries().Where(x => x.Entity is IAuditable && (x.State == EntityState.Added || x.State == EntityState.Modified));
foreach (DbEntityEntry entry in entities)
{
if (entry.Entity is IAuditable)
{
IAuditable auditable = ((IAuditable)entry.Entity);
if (entry.State == EntityState.Added)
{
if (auditable.CreatedOn == DateTime.MinValue)
{
auditable.CreatedOn = TrendyolApp.Instance.DateTimeProvider.Now;
if (SetUpdatedOnSameAsCreatedOnForNewObjects)
{
auditable.UpdatedOn = auditable.CreatedOn;
}
}
if (String.IsNullOrEmpty(auditable.CreatedBy))
{
auditable.CreatedBy = currentUser;
}
}
else
{
if (!auditable.UpdatedOn.HasValue)
{
auditable.UpdatedOn = TrendyolApp.Instance.DateTimeProvider.Now;
}
auditable.UpdatedBy = currentUser;
}
}
}
}
public virtual TId GetNextId<TEntity, TId>() where TEntity : IEntity<TId>
{
string sequenceName = GetSequenceName<TEntity, TId>();
var sql = $"SELECT (NEXT VALUE FOR {sequenceName})";
return GetSequenceId<TId>(sql,sequenceName);
}
public virtual TId GetNextIdRange<TEntity, TId>(int rangeSize) where TEntity : IEntity<TId>
{
var sequenceName = GetSequenceName<TEntity, TId>();
var sql = $@"
DECLARE @range_first_value sql_variant ,
@range_first_value_output sql_variant ;
EXEC sp_sequence_get_range
@sequence_name = N'{sequenceName}'
, @range_size = {rangeSize}
, @range_first_value = @range_first_value_output OUTPUT ;
SELECT @range_first_value_output AS FirstNumber ;";
return GetSequenceId<TId>(sql,sequenceName);
}
private static string GetSequenceName<TEntity, TId>() where TEntity : IEntity<TId>
{
Type entityType = typeof(TEntity);
SequenceAttribute attribute = entityType.GetCustomAttribute<SequenceAttribute>();
if (attribute == null)
{
throw new InvalidOperationException("You need to decorate your entity with Sequence attribute to use this extension method.");
}
string sequenceName = attribute.Name;
return sequenceName;
}
private TId GetSequenceId<TId>(string sql,string sequenceName)
{
var id = Database.SqlQuery<TId>(sql).FirstOrDefault();
if (id == null || id.Equals(default(TId)))
throw new InvalidOperationException($"Database did not return an instance of identity for sequence {sequenceName}.");
return id;
}
private void InitializeContext(bool logExecutedQueries)
{
Configuration.LazyLoadingEnabled = false;
Configuration.ProxyCreationEnabled = false;
if (logExecutedQueries)
{
Database.Log = Logger.Trace;
}
}
}
}