forked from Avanade/Beef
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathEfDbBase.cs
342 lines (290 loc) · 16.4 KB
/
EfDbBase.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
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
// Copyright (c) Avanade. Licensed under the MIT License. See https://github.com/Avanade/Beef
using Beef.Data.Database;
using Beef.Entities;
using Beef.Mapper;
using Microsoft.Data.SqlClient;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace Beef.Data.EntityFrameworkCore
{
/// <summary>
/// Represents the core base class for encapsulating the database access layer using entity framework.
/// </summary>
public abstract class EfDbBase
{
/// <summary>
/// Transforms and throws the <see cref="IBusinessException"/> equivalent for a <see cref="SqlException"/>.
/// </summary>
/// <param name="sex">The <see cref="SqlException"/>.</param>
public static void ThrowTransformedSqlException(SqlException sex)
{
if (sex == null)
throw new ArgumentNullException(nameof(sex));
var msg = sex.Message?.TrimEnd();
switch (sex.Number)
{
case 56001: throw new ValidationException(msg, sex);
case 56002: throw new BusinessException(msg, sex);
case 56003: throw new AuthorizationException(msg, sex);
case 56004: throw new ConcurrencyException(msg, sex);
case 56005: throw new NotFoundException(msg, sex);
case 56006: throw new ConflictException(msg, sex);
case 56007: throw new DuplicateException(msg, sex);
default:
if (AlwaysCheckSqlDuplicateErrorNumbers && SqlDuplicateErrorNumbers.Contains(sex.Number))
throw new DuplicateException(null, sex);
break;
}
}
/// <summary>
/// Indicates whether to always check the <see cref="SqlDuplicateErrorNumbers"/> when executing the <see cref="ThrowTransformedSqlException(SqlException)"/> method.
/// </summary>
public static bool AlwaysCheckSqlDuplicateErrorNumbers { get; set; } = true;
/// <summary>
/// Gets or sets the list of known <see cref="SqlException.Number"/> values for the <see cref="ThrowTransformedSqlException(SqlException)"/> method.
/// </summary>
public static List<int> SqlDuplicateErrorNumbers { get; } = new List<int>(new int[] { 2601, 2627 });
/// <summary>
/// Gets the <b>Entity Framework</b> keys from the specified keys.
/// </summary>
/// <param name="keys">The key values.</param>
/// <returns>The <b>Entity Framework</b> key values.</returns>
public static object?[] GetEfKeys(IComparable?[] keys)
{
if (keys == null || keys.Length == 0)
throw new ArgumentNullException(nameof(keys));
return keys;
}
/// <summary>
/// Gets the converted <b>Entity Framework</b> keys from the entity value.
/// </summary>
/// <param name="value">The entity value.</param>
/// <returns>The <b>Entity Framework</b> key values.</returns>
public static object?[] GetEfKeys(object value) => value switch
{
IStringIdentifier si => new object?[] { si.Id! },
IGuidIdentifier gi => new object?[] { gi.Id },
IInt32Identifier ii => new object?[] { ii.Id! },
IInt64Identifier il => new object?[] { il.Id! },
IUniqueKey uk => uk.UniqueKey.Args,
_ => throw new NotSupportedException($"Value Type must be {nameof(IStringIdentifier)}, {nameof(IGuidIdentifier)}, {nameof(IInt32Identifier)}, {nameof(IInt64Identifier)}, or {nameof(IUniqueKey)}."),
};
}
/// <summary>
/// Represents the base class for encapsulating the database access layer using an entity framework <see cref="Microsoft.EntityFrameworkCore.DbContext"/>.
/// </summary>
/// <typeparam name="TDbContext">The <see cref="DbContext"/> <see cref="Type"/>.</typeparam>
public abstract class EfDbBase<TDbContext> : EfDbBase, IEfDb<TDbContext> where TDbContext : DbContext, IEfDbContext
{
/// <summary>
/// Initializes a new instance of the <see cref="EfDbBase{TDbContext}"/> class.
/// </summary>
/// <param name="dbContext">The <see cref="Microsoft.EntityFrameworkCore.DbContext"/>.</param>
/// <param name="invoker">Enables the <see cref="Invoker"/> to be overridden; defaults to <see cref="EfDbInvoker{TDbContext}"/>.</param>
public EfDbBase(TDbContext dbContext, EfDbInvoker<TDbContext>? invoker = null)
{
DbContext = dbContext ?? throw new ArgumentNullException(nameof(dbContext));
Invoker = invoker ?? new EfDbInvoker<TDbContext>();
}
/// <summary>
/// Gets the underlying <typeparamref name="TDbContext"/> instance.
/// </summary>
/// <returns>The <typeparamref name="TDbContext"/> instance.</returns>
public TDbContext DbContext { get; private set; }
/// <summary>
/// Gets the <see cref="EfDbInvoker{TDbContext}"/>.
/// </summary>
public EfDbInvoker<TDbContext> Invoker { get; private set; }
/// <summary>
/// Gets the <see cref="DatabaseEventOutboxInvoker"/> from the <see cref="IEfDbContext.BaseDatabase"/>.
/// </summary>
/// <returns>The <see cref="IDatabase.EventOutboxInvoker"/>.</returns>
public DatabaseEventOutboxInvoker EventOutboxInvoker => DbContext.BaseDatabase.EventOutboxInvoker;
/// <summary>
/// Gets or sets the <see cref="DatabaseWildcard"/> to enable wildcard replacement.
/// </summary>
public DatabaseWildcard Wildcard { get; set; } = new DatabaseWildcard();
/// <summary>
/// Gets or sets the <see cref="SqlException"/> handler (by default set up to execute <see cref="EfDbBase.ThrowTransformedSqlException(SqlException)"/>).
/// </summary>
public Action<SqlException> ExceptionHandler { get; set; } = (sex) => ThrowTransformedSqlException(sex);
/// <summary>
/// Invokes the <paramref name="action"/> whilst <see cref="DatabaseWildcard.Replace(string)">replacing</see> the <b>wildcard</b> characters when the <paramref name="with"/> is not <c>null</c>.
/// </summary>
/// <param name="with">The value with which to verify.</param>
/// <param name="action">The <see cref="Action"/> to invoke when there is a valid <paramref name="with"/> value; passed the database specific wildcard value.</param>
public void WithWildcard(string? with, Action<string> action)
{
if (with != null)
{
with = Wildcard.Replace(with);
if (with != null)
action?.Invoke(with);
}
}
/// <summary>
/// Invokes the <paramref name="action"/> when the <paramref name="with"/> is not the default value for the <see cref="Type"/>.
/// </summary>
/// <typeparam name="T">The with value <see cref="Type"/>.</typeparam>
/// <param name="with">The value with which to verify.</param>
/// <param name="action">The <see cref="Action"/> to invoke when there is a valid <paramref name="with"/> value.</param>
public void With<T>(T with, Action action)
{
if (Comparer<T>.Default.Compare(with, default) != 0 && Comparer<T>.Default.Compare(with, default) != 0)
{
if (!(with is string) && with is System.Collections.IEnumerable ie && !ie.GetEnumerator().MoveNext())
return;
action?.Invoke();
}
}
/// <summary>
/// Creates an <see cref="EfDbQuery{T, TModel, TDbContext}"/> to enable select-like capabilities.
/// </summary>
/// <typeparam name="T">The resultant <see cref="Type"/>.</typeparam>
/// <typeparam name="TModel">The entity framework model <see cref="Type"/>.</typeparam>
/// <param name="args">The <see cref="EfDbArgs"/>.</param>
/// <param name="query">The function to further define the query.</param>
/// <returns>A <see cref="EfDbQuery{T, TModel, TDbContext}"/>.</returns>
public IEfDbQuery<T, TModel> Query<T, TModel>(EfDbArgs args, Func<IQueryable<TModel>, IQueryable<TModel>>? query = null) where T : class, new() where TModel : class, new()
=> new EfDbQuery<T, TModel, TDbContext>(this, args, query);
/// <summary>
/// Gets the entity for the specified <paramref name="keys"/> mapping from <typeparamref name="TModel"/> to <typeparamref name="T"/>.
/// </summary>
/// <typeparam name="T">The resultant <see cref="Type"/>.</typeparam>
/// <typeparam name="TModel">The entity framework model <see cref="Type"/>.</typeparam>
/// <param name="args">The <see cref="EfDbArgs"/>.</param>
/// <param name="keys">The key values.</param>
/// <returns>The entity value where found; otherwise, <c>null</c>.</returns>
public async Task<T?> GetAsync<T, TModel>(EfDbArgs args, params IComparable[] keys) where T : class, new() where TModel : class, new()
{
if (args == null)
throw new ArgumentNullException(nameof(args));
var efKeys = GetEfKeys(keys);
return await Invoker.InvokeAsync(this, async () =>
{
return await FindAsync<T, TModel>(args, efKeys).ConfigureAwait(false);
}, this).ConfigureAwait(false);
}
/// <summary>
/// Performs a create for the value (reselects and/or automatically saves changes where specified).
/// </summary>
/// <typeparam name="T">The resultant <see cref="Type"/>.</typeparam>
/// <typeparam name="TModel">The entity framework model <see cref="Type"/>.</typeparam>
/// <param name="args">The <see cref="EfDbArgs"/>.</param>
/// <param name="value">The value to insert.</param>
/// <returns>The value (refreshed where specified).</returns>
public async Task<T> CreateAsync<T, TModel>(EfDbArgs args, T value) where T : class, new() where TModel : class, new()
{
CheckSaveArgs<T, TModel>(args);
if (value == null)
throw new ArgumentNullException(nameof(value));
if (value is IChangeLog cl)
{
if (cl.ChangeLog == null)
cl.ChangeLog = new ChangeLog();
cl.ChangeLog.CreatedBy = ExecutionContext.HasCurrent ? ExecutionContext.Current.Username : ExecutionContext.EnvironmentUsername;
cl.ChangeLog.CreatedDate = ExecutionContext.HasCurrent ? ExecutionContext.Current.Timestamp : Cleaner.Clean(DateTime.Now);
}
return await Invoker.InvokeAsync(this, async () =>
{
TModel model = args.Mapper.Map<T, TModel>(value, Mapper.OperationTypes.Create) ?? throw new InvalidOperationException("Mapping to the EF entity must not result in a null value.");
// On create the tenant id must have a value specified.
if (model is IMultiTenant mt)
mt.TenantId = ExecutionContext.Current.TenantId;
DbContext.Add(model);
if (args.SaveChanges)
await DbContext.SaveChangesAsync(true).ConfigureAwait(false);
return args.Refresh ? args.Mapper.Map<TModel, T>(model, Mapper.OperationTypes.Get)! : value;
}, this).ConfigureAwait(false);
}
/// <summary>
/// Performs an update for the value (reselects and/or automatically saves changes where specified).
/// </summary>
/// <typeparam name="T">The resultant <see cref="Type"/>.</typeparam>
/// <typeparam name="TModel">The entity framework model <see cref="Type"/>.</typeparam>
/// <param name="args">The <see cref="EfDbArgs"/>.</param>
/// <param name="value">The value to insert.</param>
/// <returns>The value (refreshed where specified).</returns>
public async Task<T> UpdateAsync<T, TModel>(EfDbArgs args, T value) where T : class, new() where TModel : class, new()
{
CheckSaveArgs<T, TModel>(args);
if (value == null)
throw new ArgumentNullException(nameof(value));
if (value is IChangeLog cl)
{
if (cl.ChangeLog == null)
cl.ChangeLog = new ChangeLog();
cl.ChangeLog.UpdatedBy = ExecutionContext.HasCurrent ? ExecutionContext.Current.Username : ExecutionContext.EnvironmentUsername;
cl.ChangeLog.UpdatedDate = ExecutionContext.HasCurrent ? ExecutionContext.Current.Timestamp : Cleaner.Clean(DateTime.Now);
}
return await Invoker.InvokeAsync(this, async () =>
{
// Check (find) if the entity exists.
var efKeys = GetEfKeys(value);
var model = (TModel)await DbContext.FindAsync(typeof(TModel), efKeys).ConfigureAwait(false);
if (model == null)
throw new NotFoundException();
// Remove the entity from the tracker before we attempt to update; otherwise, will use existing rowversion and concurrency will not work as expected.
DbContext.Remove(model);
DbContext.ChangeTracker.AcceptAllChanges();
args.Mapper.Map<T, TModel>(value, model, Mapper.OperationTypes.Update);
DbContext.Update(model);
if (args.SaveChanges)
await DbContext.SaveChangesAsync(true).ConfigureAwait(false);
return args.Refresh ? args.Mapper.Map<TModel, T>(model, Mapper.OperationTypes.Get)! : value;
}, this).ConfigureAwait(false);
}
/// <summary>
/// Performs a delete for the specified <paramref name="keys"/>.
/// </summary>
/// <typeparam name="T">The resultant <see cref="Type"/>.</typeparam>
/// <typeparam name="TModel">The entity framework model <see cref="Type"/>.</typeparam>
/// <param name="args">The <see cref="EfDbArgs"/>.</param>
/// <param name="keys">The key values.</param>
/// <remarks>Where the model implements <see cref="ILogicallyDeleted"/> then this will update the <see cref="ILogicallyDeleted.IsDeleted"/> with <c>true</c> versus perform a physical deletion.</remarks>
public async Task DeleteAsync<T, TModel>(EfDbArgs args, params IComparable[] keys) where T : class, new() where TModel : class, new()
{
CheckSaveArgs<T, TModel>(args);
var efKeys = GetEfKeys(keys);
await Invoker.InvokeAsync(this, async () =>
{
// A pre-read is required to get the row version for concurrency.
var model = (TModel)await DbContext.FindAsync(typeof(TModel), efKeys).ConfigureAwait(false);
if (model == null)
throw new NotFoundException();
if (model is ILogicallyDeleted emld)
{
emld.IsDeleted = true;
DbContext.Update(model);
}
else
DbContext.Remove(model);
if (args.SaveChanges)
await DbContext.SaveChangesAsync(true).ConfigureAwait(false);
}, this).ConfigureAwait(false);
}
/// <summary>
/// Check the consistency of the save arguments.
/// </summary>
private static void CheckSaveArgs<T, TModel>(EfDbArgs saveArgs) where T : class, new() where TModel : class, new()
{
if (saveArgs == null)
throw new ArgumentNullException(nameof(saveArgs));
if (saveArgs.Refresh && !saveArgs.SaveChanges)
throw new ArgumentException("The Refresh property cannot be set to true without the SaveChanges also being set to true (given the save will occur after this method call).", nameof(saveArgs));
}
/// <summary>
/// Performs the EF select single (find).
/// </summary>
private async Task<T> FindAsync<T, TModel>(EfDbArgs args, object?[] keys) where T : class, new() where TModel : class, new()
{
var model = await DbContext.FindAsync<TModel>(keys).ConfigureAwait(false);
if (model == default)
return default!;
return args.Mapper.Map<T>(model) ?? throw new InvalidOperationException("Mapping from the EF entity must not result in a null value.");
}
}
}