| | | 1 | | using System.Reflection; |
| | | 2 | | using Microsoft.EntityFrameworkCore.Infrastructure; |
| | | 3 | | |
| | | 4 | | namespace ZhEaIsNsAaBn.Infrastructure.Core; |
| | | 5 | | |
| | | 6 | | /// <summary>When and by whom: one value for every row of one save or bulk operation.</summary> |
| | | 7 | | /// <param name="Now">The local time from the <see cref="TimeProvider"/>.</param> |
| | | 8 | | /// <param name="UserId">The user key (boxed <c>TId</c>).</param> |
| | | 9 | | /// <param name="UserName">The user name.</param> |
| | | 10 | | internal readonly record struct AuditStamp( DateTime Now, object UserId, string UserName ); |
| | | 11 | | |
| | | 12 | | /// <summary>The non-generic face of <see cref="AuditInterceptor{TId}"/>, used by the bulk operations (which don't know |
| | | 13 | | internal interface IAuditStamper |
| | | 14 | | { |
| | | 15 | | /// <summary>The user key type.</summary> |
| | | 16 | | Type IdType { get; } |
| | | 17 | | |
| | | 18 | | /// <summary>The current user (else the system user) and the current time.</summary> |
| | | 19 | | AuditStamp Stamp(); |
| | | 20 | | |
| | | 21 | | /// <summary>Whether <paramref name="entityType"/> is deleted for real despite a soft-delete flag.</summary> |
| | | 22 | | bool IsHardDelete( Type entityType ); |
| | | 23 | | } |
| | | 24 | | |
| | | 25 | | internal static class AuditStamperExtensions |
| | | 26 | | { |
| | | 27 | | /// <summary>The auditing interceptor added to this context's options, or <see langword="null"/>.</summary> |
| | | 28 | | internal static IAuditStamper? FindAuditStamper( this DbContext context ) |
| | 44 | 29 | | => context.GetService<IDbContextOptions>().FindExtension<CoreOptionsExtension>()?.Interceptors?.OfType<IAuditSta |
| | | 30 | | |
| | | 31 | | /// <summary>The interceptor, or a clear <see cref="InvalidOperationException"/>.</summary> |
| | | 32 | | internal static IAuditStamper RequireAuditStamper( this DbContext context ) |
| | 44 | 33 | | => context.FindAuditStamper() |
| | 44 | 34 | | ?? throw new InvalidOperationException( $"Auditing is not enabled for {context.GetType().Name}: add .WithAudi |
| | 44 | 35 | | + "(or options.UseAuditing<TId>( … ))." ); |
| | | 36 | | |
| | | 37 | | /// <summary>Checks that a *ById property holds the stamper's key type (TId or TId?).</summary> |
| | | 38 | | internal static void CheckIdType( this IAuditStamper stamper, Type entityType, PropertyInfo property ) |
| | | 39 | | { |
| | 168 | 40 | | var type = Nullable.GetUnderlyingType( property.PropertyType ) ?? property.PropertyType; |
| | | 41 | | |
| | 168 | 42 | | if ( type != stamper.IdType ) |
| | | 43 | | { |
| | 0 | 44 | | throw new InvalidOperationException( $"{entityType.Name}.{property.Name} is {property.PropertyType.Name}, bu |
| | | 45 | | } |
| | 168 | 46 | | } |
| | | 47 | | } |