-
Notifications
You must be signed in to change notification settings - Fork 0
/
UnitOfWork.cs
executable file
·203 lines (163 loc) · 6.95 KB
/
UnitOfWork.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
190
191
192
193
194
195
196
197
198
199
200
201
202
203
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using CustomFramework.Data.Models;
using CustomFramework.Data.Repositories;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Storage;
using System.Reflection;
//https://github.com/Arch/UnitOfWork/blob/master/src/Microsoft.EntityFrameworkCore.UnitOfWork/UnitOfWork.cs
namespace CustomFramework.Data
{
public class UnitOfWork<TContext> : IRepositoryFactory, IUnitOfWork<TContext> where TContext : DbContext
{
private bool _disposed;
private Dictionary<Type, object> _repositories;
protected UnitOfWork(TContext context)
{
DbContext = context ?? throw new ArgumentNullException(nameof(context));
}
public TContext DbContext { get; }
public BaseRepository<TEntity, TKey> GetRepository<TEntity, TKey>() where TEntity : BaseModel<TKey>
{
if (_repositories == null)
{
_repositories = new Dictionary<Type, object>();
}
var type = typeof(TEntity);
if (!_repositories.ContainsKey(type))
{
_repositories[type] = new BaseRepository<TEntity, TKey>(DbContext);
}
return (BaseRepository<TEntity, TKey>)_repositories[type];
}
public BaseRepositoryNonUser<TEntity, TKey> GetRepositoryNonUser<TEntity, TKey>() where TEntity : BaseModelNonUser<TKey>
{
if (_repositories == null)
{
_repositories = new Dictionary<Type, object>();
}
var type = typeof(TEntity);
if (!_repositories.ContainsKey(type))
{
_repositories[type] = new BaseRepositoryNonUser<TEntity, TKey>(DbContext);
}
return (BaseRepositoryNonUser<TEntity, TKey>)_repositories[type];
}
public int ExecuteSqlCommand(string sql, params object[] parameters) => DbContext.Database.ExecuteSqlCommand(sql, parameters);
public IQueryable<TEntity> FromSql<TEntity>(string sql, params object[] parameters) where TEntity : class => DbContext.Set<TEntity>().FromSql(sql, parameters);
public int SaveChanges()
{
return DbContext.SaveChanges();
}
public List<EntityChange> GetChanges<TEntity>()
{
var entityChanges = new List<EntityChange>();
var modifiedEntities = DbContext.ChangeTracker.Entries()
.Where(p => p.State == EntityState.Modified || p.State == EntityState.Added || p.State == EntityState.Deleted || p.State == EntityState.Modified || p.State == EntityState.Detached).ToList();
foreach (var change in modifiedEntities)
{
var entityName = change.Entity.GetType().Name;
var entityIdObj = change.Property("Id").CurrentValue;
long? entityId = null;
if (entityIdObj != null) entityId = Convert.ToInt64(entityIdObj.ToString());
foreach (var prop in change.Entity.GetType().GetTypeInfo().DeclaredProperties)
{
if (!prop.GetGetMethod().IsVirtual)
{
object oldValueObj = null;
object newValueObj = null;
if (change.State == EntityState.Deleted || change.State == EntityState.Modified)
{
oldValueObj = change.GetDatabaseValues().GetValue<object>(prop.Name);
}
if (change.State == EntityState.Added || change.State == EntityState.Modified)
{
newValueObj = change.Property(prop.Name).CurrentValue;
}
var newValue = newValueObj == null ? string.Empty : newValueObj.ToString();
var oldValue = oldValueObj == null ? string.Empty : oldValueObj.ToString();
if (oldValue != newValue)
{
entityChanges.Add(new EntityChange
{
EntityName = entityName,
FieldName = prop.Name,
IdValue = entityId,
EntityState = change.State,
OldValue = oldValue,
NewValue = newValue
});
}
}
}
}
return entityChanges;
}
public async Task<int> SaveChangesAsync()
{
OnBeforeSaving();
return await DbContext.SaveChangesAsync();
}
public async Task<int> SaveChangesAsync(params IUnitOfWork[] unitOfWorks)
{
// TransactionScope will be included in .NET Core v2.0
using (var transaction = DbContext.Database.BeginTransaction())
{
try
{
var count = 0;
foreach (var unitOfWork in unitOfWorks)
{
if (!(unitOfWork is UnitOfWork<DbContext> uow)) continue;
uow.DbContext.Database.UseTransaction(transaction.GetDbTransaction());
count += await uow.SaveChangesAsync();
}
count += await SaveChangesAsync();
transaction.Commit();
return count;
}
catch (Exception)
{
transaction.Rollback();
throw;
}
}
}
public void OnBeforeSaving()
{
var entries = DbContext?.ChangeTracker?.Entries();
if (entries == null)
{
return;
}
foreach (var entry in entries)
{
// get all the properties and are of type string
var propertyValues = entry.CurrentValues.Properties.Where(p => p.ClrType == typeof(string));
foreach (var prop in propertyValues)
{
// access the correct column by it's name and trim the value if it's not null
if (entry.CurrentValues[prop.Name] != null) entry.CurrentValues[prop.Name] = entry.CurrentValues[prop.Name].ToString().Trim();
}
}
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
protected virtual void Dispose(bool disposing)
{
if (!_disposed && disposing)
{
// clear repositories
_repositories?.Clear();
// dispose the db context.
DbContext.Dispose();
}
_disposed = true;
}
}
}