-
Notifications
You must be signed in to change notification settings - Fork 0
/
UnitOfWork.cs
302 lines (261 loc) · 11.5 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
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
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.ChangeTracking;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Storage;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
using System.Transactions;
namespace EFCore.UnitOfWork
{
public class UnitOfWork<TContext> : IRepositoryFactory, IUnitOfWork<TContext>, IUnitOfWork where TContext : DbContext
{
private readonly TContext _context;
private bool disposed = false;
private Dictionary<Type, object> repositories;
/// <summary>
/// Initializes a new instance of the <see cref="UnitOfWork{TContext}"/> class.
/// </summary>
/// <param name="context">The context.</param>
public UnitOfWork(TContext context)
{
_context = context ?? throw new ArgumentNullException(nameof(context));
}
/// <summary>
/// Gets the db context.
/// </summary>
/// <returns>The instance of type <typeparamref name="TContext"/>.</returns>
public TContext DbContext => _context;
/// <summary>
/// Changes the database name. This require the databases in the same machine. NOTE: This only work for MySQL right now.
/// </summary>
/// <param name="database">The database name.</param>
/// <remarks>
/// This only been used for supporting multiple databases in the same model. This require the databases in the same machine.
/// </remarks>
//public void ChangeDatabase(string database)
//{
// var connection = _context.Database.GetDbConnection();
// if (connection.State.HasFlag(ConnectionState.Open))
// {
// connection.ChangeDatabase(database);
// }
// else
// {
// var connectionString = Regex.Replace(connection.ConnectionString.Replace(" ", ""), @"(?<=[Dd]atabase=)\w+(?=;)", database, RegexOptions.Singleline);
// connection.ConnectionString = connectionString;
// }
// // Following code only working for mysql.
// var items = _context.Model.GetEntityTypes();
// foreach (var item in items)
// {
// if (item.Relational() is RelationalEntityTypeAnnotations extensions)
// {
// extensions.Schema = database;
// }
// }
//}
/// <summary>
/// Gets the specified repository for the <typeparamref name="TEntity"/>.
/// </summary>
/// <param name="hasCustomRepository"><c>True</c> if providing custom repositry</param>
/// <typeparam name="TEntity">The type of the entity.</typeparam>
/// <returns>An instance of type inherited from <see cref="IRepository{TEntity}"/> interface.</returns>
public IRepository<TEntity> GetRepository<TEntity>(bool hasCustomRepository = false) where TEntity : class
{
if (repositories == null)
{
repositories = new Dictionary<Type, object>();
}
// what's the best way to support custom reposity?
if (hasCustomRepository)
{
var customRepo = _context.GetService<IRepository<TEntity>>();
if (customRepo != null)
{
return customRepo;
}
}
var type = typeof(TEntity);
if (!repositories.ContainsKey(type))
{
repositories[type] = new Repository<TEntity>(_context);
}
return (IRepository<TEntity>)repositories[type];
}
/// <summary>
/// Executes the specified raw SQL command.
/// </summary>
/// <param name="sql">The raw SQL.</param>
/// <param name="parameters">The parameters.</param>
/// <returns>The number of state entities written to database.</returns>
//public int ExecuteSqlCommand(string sql, params object[] parameters) => _context.Database.ExecuteSqlCommand(sql, parameters);
/// <summary>
/// Uses raw SQL queries to fetch the specified <typeparamref name="TEntity" /> data.
/// </summary>
/// <typeparam name="TEntity">The type of the entity.</typeparam>
/// <param name="sql">The raw SQL.</param>
/// <param name="parameters">The parameters.</param>
/// <returns>An <see cref="IQueryable{T}" /> that contains elements that satisfy the condition specified by raw SQL.</returns>
//public IQueryable<TEntity> FromSql<TEntity>(string sql, params object[] parameters) where TEntity : class => _context.Set<TEntity>().FromSql(sql, parameters);
/// <summary>
/// Saves all changes made in this context to the database.
/// </summary>
/// <param name="ensureAutoHistory"><c>True</c> if save changes ensure auto record the change history.</param>
/// <returns>The number of state entries written to the database.</returns>
public int SaveChanges(bool ensureAutoHistory = false)
{
if (ensureAutoHistory)
{
_context.EnsureAutoHistory();
}
return _context.SaveChanges();
}
/// <summary>
/// Asynchronously saves all changes made in this unit of work to the database.
/// </summary>
/// <param name="ensureAutoHistory"><c>True</c> if save changes ensure auto record the change history.</param>
/// <returns>A <see cref="Task{TResult}"/> that represents the asynchronous save operation. The task result contains the number of state entities written to database.</returns>
public async Task<int> SaveChangesAsync(bool ensureAutoHistory = false)
{
if (ensureAutoHistory)
{
_context.EnsureAutoHistory();
}
return await _context.SaveChangesAsync();
}
/// <summary>
/// Saves all changes made in this context to the database with distributed transaction.
/// </summary>
/// <param name="ensureAutoHistory"><c>True</c> if save changes ensure auto record the change history.</param>
/// <param name="unitOfWorks">An optional <see cref="IUnitOfWork"/> array.</param>
/// <returns>A <see cref="Task{TResult}"/> that represents the asynchronous save operation. The task result contains the number of state entities written to database.</returns>
public async Task<int> SaveChangesAsync(bool ensureAutoHistory = false, params IUnitOfWork[] unitOfWorks)
{
using (var ts = new TransactionScope())
{
var count = 0;
foreach (var unitOfWork in unitOfWorks)
{
count += await unitOfWork.SaveChangesAsync(ensureAutoHistory);
}
count += await SaveChangesAsync(ensureAutoHistory);
ts.Complete();
return count;
}
}
/// <summary>
/// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
/// </summary>
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
/// <summary>
/// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
/// </summary>
/// <param name="disposing">The disposing.</param>
protected virtual void Dispose(bool disposing)
{
if (!disposed)
{
if (disposing)
{
// clear repositories
if (repositories != null)
{
repositories.Clear();
}
// dispose the db context.
_context.Dispose();
}
}
disposed = true;
}
public void TrackGraph(object rootEntity, Action<EntityEntryGraphNode> callback)
{
_context.ChangeTracker.TrackGraph(rootEntity, callback);
}
public IDbContextTransaction BeginTransaction()
{
return _context.Database.BeginTransaction();
}
public void RollBackChanges()
{
var changedEntries = _context.ChangeTracker.Entries()
.Where(x => x.State != EntityState.Unchanged).ToList();
foreach (var entry in changedEntries)
{
switch (entry.State)
{
case EntityState.Modified:
entry.CurrentValues.SetValues(entry.OriginalValues);
entry.State = EntityState.Unchanged;
break;
case EntityState.Added:
entry.State = EntityState.Detached;
break;
case EntityState.Deleted:
entry.State = EntityState.Unchanged;
break;
}
}
}
public void ChangeDatabase(string database)
{
throw new NotImplementedException();
}
public int ExecuteSqlCommand(string sql, params object[] parameters)
{
throw new NotImplementedException();
}
public IQueryable<TEntity> FromSql<TEntity>(string sql, params object[] parameters) where TEntity : class
{
throw new NotImplementedException();
}
public Task<List<T>> GetFromRawSqlAsync<T>(string sql, CancellationToken cancellationToken = default)
{
if (string.IsNullOrWhiteSpace(sql))
{
throw new ArgumentNullException(nameof(sql));
}
IEnumerable<object> parameters = new List<object>();
return _context.GetFromQueryAsync<T>(sql, parameters, cancellationToken);
}
public Task<List<T>> GetFromRawSqlAsync<T>(string sql, object parameter, CancellationToken cancellationToken = default)
{
if (string.IsNullOrWhiteSpace(sql))
{
throw new ArgumentNullException(nameof(sql));
}
List<object> parameters = new List<object>() { parameter };
return _context.GetFromQueryAsync<T>(sql, parameters, cancellationToken);
}
public Task<List<T>> GetFromRawSqlAsync<T>(string sql, IEnumerable<object> parameters, CancellationToken cancellationToken = default)
{
if (string.IsNullOrWhiteSpace(sql))
{
throw new ArgumentNullException(nameof(sql));
}
return _context.GetFromQueryAsync<T>(sql, parameters, cancellationToken);
}
public Task<int> ExecuteSqlCommandAsync(string sql, CancellationToken cancellationToken = default)
{
return _context.Database.ExecuteSqlRawAsync(sql, cancellationToken);
}
public Task<int> ExecuteSqlCommandAsync(string sql, params object[] parameters)
{
return _context.Database.ExecuteSqlRawAsync(sql, parameters);
}
public Task<int> ExecuteSqlCommandAsync(string sql, IEnumerable<object> parameters, CancellationToken cancellationToken = default)
{
return _context.Database.ExecuteSqlRawAsync(sql, parameters, cancellationToken);
}
}
}