| | | 1 | | using ArturRios.Data.Relational.Core.Configuration; |
| | | 2 | | using ArturRios.Data.Relational.Core.Entities; |
| | | 3 | | using ArturRios.Data.Relational.Core.Interfaces; |
| | | 4 | | using ArturRios.Output; |
| | | 5 | | using Microsoft.EntityFrameworkCore; |
| | | 6 | | |
| | | 7 | | namespace ArturRios.Data.Relational.Core.Repositories; |
| | | 8 | | |
| | | 9 | | /// <summary> |
| | | 10 | | /// Provider-agnostic Entity Framework Core implementation of the repository contracts. |
| | | 11 | | /// Every write auto-saves; inside an active unit-of-work transaction, |
| | | 12 | | /// saves flush without committing. Infrastructure failures are returned as <see cref="DataOutput{T}" /> errors; |
| | | 13 | | /// a failed write discards the changes still pending in the context, so the context stays usable. |
| | | 14 | | /// </summary> |
| | | 15 | | /// <typeparam name="T">The entity type.</typeparam> |
| | | 16 | | /// <typeparam name="TKey">The entity's primary key type.</typeparam> |
| | | 17 | | /// <param name="context">The application's <see cref="BaseDbContext" />.</param> |
| | 114 | 18 | | public class EfRepository<T, TKey>(BaseDbContext context) : IRepository<T, TKey>, IAsyncRepository<T, TKey> |
| | | 19 | | where T : Entity<TKey> where TKey : IEquatable<TKey> |
| | | 20 | | { |
| | | 21 | | /// <summary>Message returned when an optimistic-concurrency conflict is detected.</summary> |
| | | 22 | | protected const string ConcurrencyMessage = RelationalErrors.ConcurrencyMessage; |
| | | 23 | | |
| | | 24 | | /// <summary>Message returned when a persistence operation fails with no finer classification.</summary> |
| | | 25 | | protected const string PersistenceMessage = RelationalErrors.GenericMessage; |
| | | 26 | | |
| | | 27 | | /// <summary>Message returned when a write violates a unique constraint.</summary> |
| | | 28 | | protected const string UniqueViolationMessage = RelationalErrors.UniqueViolationMessage; |
| | | 29 | | |
| | | 30 | | /// <summary>The tracked entity set for <typeparamref name="T" />.</summary> |
| | 200 | 31 | | protected DbSet<T> Set => context.Set<T>(); |
| | | 32 | | |
| | | 33 | | /// <inheritdoc /> |
| | | 34 | | public Task<DataOutput<IEnumerable<T>>> GetAllAsync(CancellationToken ct = default) => |
| | 16 | 35 | | GuardedAsync<IEnumerable<T>>(async () => await Set.ToListAsync(ct).ConfigureAwait(false)); |
| | | 36 | | |
| | | 37 | | /// <inheritdoc /> |
| | | 38 | | public Task<DataOutput<T?>> GetByIdAsync(TKey id, CancellationToken ct = default) => |
| | 16 | 39 | | GuardedAsync(async () => await Set.FirstOrDefaultAsync(e => e.Id.Equals(id), ct).ConfigureAwait(false)); |
| | | 40 | | |
| | | 41 | | /// <inheritdoc /> |
| | | 42 | | public Task<DataOutput<TKey>> CreateAsync(T entity, CancellationToken ct = default) => |
| | 20 | 43 | | WriteAsync(async () => |
| | 20 | 44 | | { |
| | 20 | 45 | | await Set.AddAsync(entity, ct).ConfigureAwait(false); |
| | 20 | 46 | | await context.SaveChangesAsync(ct).ConfigureAwait(false); |
| | 20 | 47 | | |
| | 18 | 48 | | return entity.Id; |
| | 38 | 49 | | }); |
| | | 50 | | |
| | | 51 | | /// <inheritdoc /> |
| | | 52 | | public Task<DataOutput<IEnumerable<TKey>>> |
| | | 53 | | CreateRangeAsync(IEnumerable<T> entities, CancellationToken ct = default) => |
| | 4 | 54 | | WriteAsync<IEnumerable<TKey>>(async () => |
| | 4 | 55 | | { |
| | 4 | 56 | | var list = entities.ToList(); |
| | 4 | 57 | | await Set.AddRangeAsync(list, ct).ConfigureAwait(false); |
| | 4 | 58 | | await context.SaveChangesAsync(ct).ConfigureAwait(false); |
| | 4 | 59 | | |
| | 12 | 60 | | return list.Select(e => e.Id).ToList(); |
| | 8 | 61 | | }); |
| | | 62 | | |
| | | 63 | | /// <inheritdoc /> |
| | | 64 | | public Task<DataOutput<T>> UpdateAsync(T entity, CancellationToken ct = default) => |
| | 2 | 65 | | WriteAsync(async () => |
| | 2 | 66 | | { |
| | 2 | 67 | | Set.Update(entity); |
| | 2 | 68 | | await context.SaveChangesAsync(ct).ConfigureAwait(false); |
| | 2 | 69 | | |
| | 2 | 70 | | return entity; |
| | 4 | 71 | | }); |
| | | 72 | | |
| | | 73 | | /// <inheritdoc /> |
| | | 74 | | public Task<DataOutput<IEnumerable<T>>> UpdateRangeAsync(IEnumerable<T> entities, CancellationToken ct = default) => |
| | 0 | 75 | | WriteAsync<IEnumerable<T>>(async () => |
| | 0 | 76 | | { |
| | 0 | 77 | | var list = entities.ToList(); |
| | 0 | 78 | | Set.UpdateRange(list); |
| | 0 | 79 | | await context.SaveChangesAsync(ct).ConfigureAwait(false); |
| | 0 | 80 | | |
| | 0 | 81 | | return list; |
| | 0 | 82 | | }); |
| | | 83 | | |
| | | 84 | | /// <inheritdoc /> |
| | | 85 | | public Task<DataOutput<TKey>> DeleteAsync(T entity, CancellationToken ct = default) => |
| | 4 | 86 | | WriteAsync(async () => |
| | 4 | 87 | | { |
| | 4 | 88 | | Set.Remove(entity); |
| | 4 | 89 | | await context.SaveChangesAsync(ct).ConfigureAwait(false); |
| | 4 | 90 | | |
| | 4 | 91 | | return entity.Id; |
| | 8 | 92 | | }); |
| | | 93 | | |
| | | 94 | | /// <inheritdoc /> |
| | | 95 | | public Task<DataOutput<IEnumerable<TKey>>> DeleteRangeAsync(IEnumerable<TKey> ids, CancellationToken ct = default) = |
| | 2 | 96 | | WriteAsync<IEnumerable<TKey>>(async () => |
| | 2 | 97 | | { |
| | 2 | 98 | | var idList = ids.ToList(); |
| | 2 | 99 | | var matches = await Set.Where(e => idList.Contains(e.Id)).ToListAsync(ct).ConfigureAwait(false); |
| | 2 | 100 | | Set.RemoveRange(matches); |
| | 2 | 101 | | await context.SaveChangesAsync(ct).ConfigureAwait(false); |
| | 2 | 102 | | |
| | 6 | 103 | | return matches.Select(e => e.Id).ToList(); |
| | 4 | 104 | | }); |
| | | 105 | | |
| | | 106 | | /// <inheritdoc cref="Query" /> |
| | 2 | 107 | | public IQueryable<T> Query() => Set.AsQueryable(); |
| | | 108 | | |
| | | 109 | | /// <inheritdoc /> |
| | | 110 | | public DataOutput<IEnumerable<T>> GetAll() => |
| | 36 | 111 | | Guarded(IEnumerable<T> () => Set.ToList()); |
| | | 112 | | |
| | | 113 | | /// <inheritdoc /> |
| | | 114 | | public DataOutput<T?> GetById(TKey id) => |
| | 52 | 115 | | Guarded(() => Set.FirstOrDefault(e => e.Id.Equals(id))); |
| | | 116 | | |
| | | 117 | | /// <inheritdoc /> |
| | 64 | 118 | | public DataOutput<TKey> Create(T entity) => Write(() => |
| | 64 | 119 | | { |
| | 64 | 120 | | Set.Add(entity); |
| | 64 | 121 | | context.SaveChanges(); |
| | 56 | 122 | | return entity.Id; |
| | 64 | 123 | | }); |
| | | 124 | | |
| | | 125 | | /// <inheritdoc /> |
| | 8 | 126 | | public DataOutput<IEnumerable<TKey>> CreateRange(IEnumerable<T> entities) => Write(IEnumerable<TKey> () => |
| | 8 | 127 | | { |
| | 8 | 128 | | var list = entities.ToList(); |
| | 8 | 129 | | Set.AddRange(list); |
| | 8 | 130 | | context.SaveChanges(); |
| | 24 | 131 | | return list.Select(e => e.Id).ToList(); |
| | 8 | 132 | | }); |
| | | 133 | | |
| | | 134 | | /// <inheritdoc /> |
| | 20 | 135 | | public DataOutput<T> Update(T entity) => Write(() => |
| | 20 | 136 | | { |
| | 20 | 137 | | Set.Update(entity); |
| | 20 | 138 | | context.SaveChanges(); |
| | 12 | 139 | | return entity; |
| | 20 | 140 | | }); |
| | | 141 | | |
| | | 142 | | /// <inheritdoc /> |
| | 0 | 143 | | public DataOutput<IEnumerable<T>> UpdateRange(IEnumerable<T> entities) => Write(IEnumerable<T> () => |
| | 0 | 144 | | { |
| | 0 | 145 | | var list = entities.ToList(); |
| | 0 | 146 | | Set.UpdateRange(list); |
| | 0 | 147 | | context.SaveChanges(); |
| | 0 | 148 | | return list; |
| | 0 | 149 | | }); |
| | | 150 | | |
| | | 151 | | /// <inheritdoc /> |
| | 4 | 152 | | public DataOutput<TKey> Delete(T entity) => Write(() => |
| | 4 | 153 | | { |
| | 4 | 154 | | Set.Remove(entity); |
| | 4 | 155 | | context.SaveChanges(); |
| | 2 | 156 | | return entity.Id; |
| | 4 | 157 | | }); |
| | | 158 | | |
| | | 159 | | /// <inheritdoc /> |
| | 4 | 160 | | public DataOutput<IEnumerable<TKey>> DeleteRange(IEnumerable<TKey> ids) => Write(IEnumerable<TKey> () => |
| | 4 | 161 | | { |
| | 4 | 162 | | var idList = ids.ToList(); |
| | 4 | 163 | | var matches = Set.Where(e => idList.Contains(e.Id)).ToList(); |
| | 4 | 164 | | Set.RemoveRange(matches); |
| | 4 | 165 | | context.SaveChanges(); |
| | 10 | 166 | | return matches.Select(e => e.Id).ToList(); |
| | 4 | 167 | | }); |
| | | 168 | | |
| | | 169 | | /// <summary> |
| | | 170 | | /// Maps an exception caught by a guard to an error envelope. Provider text - constraint |
| | | 171 | | /// and index names, columns, SQL fragments, conflicting values - is classified but never |
| | | 172 | | /// returned; EF Core logs the full exception for operators. |
| | | 173 | | /// </summary> |
| | | 174 | | private static DataOutput<TResult> Fail<TResult>(Exception ex) => |
| | 24 | 175 | | DataOutput<TResult>.New.WithError(RelationalErrors.Describe(ex)); |
| | | 176 | | |
| | | 177 | | /// <summary> |
| | | 178 | | /// Runs a write, converting failures to envelope errors. A failed save leaves its changes |
| | | 179 | | /// pending in the change tracker, and the caller keeps using the same scoped context after an |
| | | 180 | | /// error envelope, so the pending changes are discarded: otherwise the next save on the context |
| | | 181 | | /// would replay the rejected change and fail again. |
| | | 182 | | /// </summary> |
| | | 183 | | private DataOutput<TResult> Write<TResult>(Func<TResult> operation) |
| | | 184 | | { |
| | | 185 | | try |
| | | 186 | | { |
| | 100 | 187 | | var output = Guarded(operation); |
| | 100 | 188 | | if (!output.Success) |
| | | 189 | | { |
| | 18 | 190 | | DiscardPendingChanges(); |
| | | 191 | | } |
| | | 192 | | |
| | 100 | 193 | | return output; |
| | | 194 | | } |
| | 0 | 195 | | catch (OperationCanceledException) |
| | | 196 | | { |
| | 0 | 197 | | DiscardPendingChanges(); |
| | 0 | 198 | | throw; |
| | | 199 | | } |
| | 100 | 200 | | } |
| | | 201 | | |
| | | 202 | | /// <inheritdoc cref="Write{TResult}" /> |
| | | 203 | | private async Task<DataOutput<TResult>> WriteAsync<TResult>(Func<Task<TResult>> operation) |
| | | 204 | | { |
| | | 205 | | try |
| | | 206 | | { |
| | 32 | 207 | | var output = await GuardedAsync(operation).ConfigureAwait(false); |
| | 32 | 208 | | if (!output.Success) |
| | | 209 | | { |
| | 2 | 210 | | DiscardPendingChanges(); |
| | | 211 | | } |
| | | 212 | | |
| | 32 | 213 | | return output; |
| | | 214 | | } |
| | 0 | 215 | | catch (OperationCanceledException) |
| | | 216 | | { |
| | 0 | 217 | | DiscardPendingChanges(); |
| | 0 | 218 | | throw; |
| | | 219 | | } |
| | 32 | 220 | | } |
| | | 221 | | |
| | | 222 | | private void DiscardPendingChanges() |
| | | 223 | | { |
| | 84 | 224 | | foreach (var entry in context.ChangeTracker.Entries() |
| | 32 | 225 | | .Where(e => e.State is EntityState.Added or EntityState.Modified or EntityState.Deleted) |
| | 20 | 226 | | .ToList()) |
| | | 227 | | { |
| | 22 | 228 | | entry.State = EntityState.Detached; |
| | | 229 | | } |
| | 20 | 230 | | } |
| | | 231 | | |
| | | 232 | | /// <summary>Runs a synchronous data operation, converting failures to envelope errors.</summary> |
| | | 233 | | protected static DataOutput<TResult> Guarded<TResult>(Func<TResult> operation) |
| | | 234 | | { |
| | | 235 | | try |
| | | 236 | | { |
| | 144 | 237 | | return DataOutput<TResult>.New.WithData(operation()); |
| | | 238 | | } |
| | 0 | 239 | | catch (OperationCanceledException) |
| | | 240 | | { |
| | 0 | 241 | | throw; |
| | | 242 | | } |
| | | 243 | | catch (Exception ex) |
| | | 244 | | { |
| | 22 | 245 | | return Fail<TResult>(ex); |
| | | 246 | | } |
| | 144 | 247 | | } |
| | | 248 | | |
| | | 249 | | /// <summary>Runs an asynchronous data operation, converting failures to envelope errors.</summary> |
| | | 250 | | protected static async Task<DataOutput<TResult>> GuardedAsync<TResult>(Func<Task<TResult>> operation) |
| | | 251 | | { |
| | | 252 | | try |
| | | 253 | | { |
| | 48 | 254 | | return DataOutput<TResult>.New.WithData(await operation().ConfigureAwait(false)); |
| | | 255 | | } |
| | 0 | 256 | | catch (OperationCanceledException) |
| | | 257 | | { |
| | 0 | 258 | | throw; |
| | | 259 | | } |
| | | 260 | | catch (Exception ex) |
| | | 261 | | { |
| | 2 | 262 | | return Fail<TResult>(ex); |
| | | 263 | | } |
| | 48 | 264 | | } |
| | | 265 | | } |