Introduces the closed generic persistence toolkit

This commit is contained in:
BinaryAlley committed 2026-09-27 21:20:35 +03:00
1 parent 9ba9b089b5
commit a632f4ced7
8 files changed
+270 -19

No files matched your search

@@ -11,4 +11,4 @@ namespace Lumina.Application.Common.DataAccess.Entities.Common;
[DebuggerDisplay("Name: {Name}")]
public record GenreEntity(
string? Name
);
) : ISharedReferenceEntity;
@@ -0,0 +1,12 @@
namespace Lumina.Application.Common.DataAccess.Entities.Common;
/// <summary>
/// Interface for a shared reference entity, whose identity is its name and whose rows are shared across the whole storage medium instead of being owned by a single parent.
/// </summary>
public interface ISharedReferenceEntity
{
/// <summary>
/// Gets the name that identifies the shared reference.
/// </summary>
string? Name { get; }
}
@@ -11,4 +11,4 @@ namespace Lumina.Application.Common.DataAccess.Entities.Common;
[DebuggerDisplay("Name: {Name}")]
public record TagEntity(
string? Name
);
) : ISharedReferenceEntity;
@@ -60,12 +60,20 @@ internal static class CollectionReconciler
{
if (shouldReplace(matchedItem, incomingItem))
{
TExisting replacementItem = createNew(incomingItem);
existingItems.Remove(matchedItem);
existingItems.Add(createNew(incomingItem));
existingItems.Add(replacementItem);
existingByKey[incomingKey] = replacementItem;
}
}
else // The desired child has no tracked counterpart, so it is added as a new child.
existingItems.Add(createNew(incomingItem));
else
{
// The desired child has no tracked counterpart, so it is added as a new child and indexed, so that a later desired child
// that reuses the same key is matched against it instead of adding a second row that would break the unique index.
TExisting addedItem = createNew(incomingItem);
existingItems.Add(addedItem);
existingByKey[incomingKey] = addedItem;
}
}
}
}
@@ -2,22 +2,26 @@
using Lumina.Application.Common.DataAccess.Entities.Common;
using Lumina.DataAccess.Core.UoW;
using Microsoft.EntityFrameworkCore;
using System;
using Microsoft.EntityFrameworkCore.ChangeTracking;
using Microsoft.EntityFrameworkCore.Metadata;
using System.Collections.Generic;
using System.Linq;
#endregion
namespace Lumina.DataAccess.Common.Persistence;
/// <summary>
/// Copies the editable scalar values of a mapped repository entity onto its tracked counterpart, while leaving the audit columns under the sole ownership of the auditing interceptor.
/// Copies the editable scalar values of a mapped repository entity onto its tracked counterpart, while leaving the primary key and the audit columns under the sole ownership of the persistence medium.
/// </summary>
internal static class EditableValuesCopier
{
/// <summary>
/// Copies the scalar values of <paramref name="incoming"/> onto the tracked <paramref name="tracked"/> entity, restoring the identity and audit columns afterwards,
/// so that the tracked row is only considered modified when an editable value actually changed.
/// Copies the scalar values of <paramref name="incoming"/> onto the tracked <paramref name="tracked"/> entity, except for its primary key and its audit columns,
/// so that the tracked row is only considered modified when an editable value actually changed, and its stored identity is never reassigned.
/// </summary>
/// <remarks>
/// The audit interceptor stamps the modification columns of the rows that are actually modified. Copying the audit columns from the mapped entity would mark untouched
/// The primary key is not copied, so that a mapped entity carrying a different, or unset, key can never retarget the tracked row. The audit interceptor stamps the
/// modification columns of the rows that are actually modified, so the audit columns are not copied either: copying them from the mapped entity would mark untouched
/// rows as modified, which would then be stamped with a change that the user never made.
/// </remarks>
/// <typeparam name="TEntity">The type of the tracked and mapped repository entity.</typeparam>
@@ -26,14 +30,24 @@ internal static class EditableValuesCopier
/// <param name="incoming">The mapped entity carrying the desired values.</param>
public static void CopyEditableValues<TEntity>(LuminaDbContext context, TEntity tracked, TEntity incoming) where TEntity : class, IAuditableEntity
{
DateTime createdOnUtc = tracked.CreatedOnUtc;
Guid createdBy = tracked.CreatedBy;
DateTime? updatedOnUtc = tracked.UpdatedOnUtc;
Guid? updatedBy = tracked.UpdatedBy;
context.Entry(tracked).CurrentValues.SetValues(incoming);
tracked.CreatedOnUtc = createdOnUtc;
tracked.CreatedBy = createdBy;
tracked.UpdatedOnUtc = updatedOnUtc;
tracked.UpdatedBy = updatedBy;
EntityEntry<TEntity> trackedEntry = context.Entry(tracked);
EntityEntry<TEntity> incomingEntry = context.Entry(incoming);
// The primary key and the audit columns are owned by the persistence medium, so they are never copied from the mapped entity.
HashSet<string> excludedProperties =
[
.. (trackedEntry.Metadata.FindPrimaryKey()?.Properties.Select(property => property.Name) ?? []),
nameof(IAuditableEntity.CreatedOnUtc),
nameof(IAuditableEntity.CreatedBy),
nameof(IAuditableEntity.UpdatedOnUtc),
nameof(IAuditableEntity.UpdatedBy)
];
foreach (IProperty property in trackedEntry.Metadata.GetProperties())
{
if (excludedProperties.Contains(property.Name))
continue;
trackedEntry.Property(property.Name).CurrentValue = incomingEntry.Property(property.Name).CurrentValue;
}
}
}
@@ -0,0 +1,132 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.DataAccess.Entities.Common;
using Lumina.DataAccess.Core.UoW;
using Lumina.Domain.Common.Primitives;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.DataAccess.Common.Persistence;
/// <summary>
/// Resolves shared reference rows, whose identity is their name, so that each distinct name is represented by a single tracked instance.
/// </summary>
/// <remarks>
/// This is the toolkit's only concern expressed over a family of entity shapes, through the <see cref="ISharedReferenceEntity"/> marker interface:
/// a shared reference is resolved by its name, the stored row wins over the incoming instance, and within-request duplicates are collapsed to one instance.
/// No per-entity method is ever needed, so a new shared reference type adds no new persistence type. A shared reference whose name is null or whitespace
/// cannot be keyed and would be lost silently, so it fails the resolution with the caller-provided error instead of being dropped.
/// </remarks>
internal static class SharedReferenceResolver
{
/// <summary>
/// Resolves the single <typeparamref name="TEntity"/> instance that represents each distinct name carried by <paramref name="incomingEntities"/>.
/// </summary>
/// <remarks>
/// The stored row wins over the incoming instance, so that a shared reference that is already persisted is reused instead of inserted again. The
/// instances are also collapsed by name, so that a name shared by several parents of the same request is only ever tracked once.
/// </remarks>
/// <typeparam name="TEntity">The type of the shared reference entity.</typeparam>
/// <param name="context">The Entity Framework context the stored rows are read through.</param>
/// <param name="incomingEntities">The shared references carried by the entity that is about to be persisted.</param>
/// <param name="invalidNameError">The error returned when a shared reference carries a name that is null or whitespace.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>A result containing either a dictionary that maps each distinct name to the single instance that represents it, or an error.</returns>
internal static async Task<Result<IReadOnlyDictionary<string, TEntity>>> ResolveAsync<TEntity>(LuminaDbContext context, IEnumerable<TEntity> incomingEntities, Error invalidNameError, CancellationToken cancellationToken)
where TEntity : class, ISharedReferenceEntity
{
// A shared reference whose name is null or whitespace cannot be keyed, and the database requires the name to be present, so the whole resolution
// fails instead of silently dropping the reference.
Dictionary<string, TEntity> resolvedByName = new(StringComparer.Ordinal);
foreach (TEntity incomingEntity in incomingEntities)
{
string? name = incomingEntity.Name;
if (string.IsNullOrWhiteSpace(name))
return invalidNameError;
resolvedByName.TryAdd(name, incomingEntity);
}
if (resolvedByName.Count == 0)
return resolvedByName;
// Prefer the instances that the context already tracks, so that a reference resolved earlier in the same request does not trigger another query.
HashSet<string> namesResolvedFromTrackedEntities = [];
foreach (TEntity trackedEntity in context.Set<TEntity>().Local)
{
string? trackedName = trackedEntity.Name;
if (!string.IsNullOrWhiteSpace(trackedName) && resolvedByName.ContainsKey(trackedName))
{
resolvedByName[trackedName] = trackedEntity;
namesResolvedFromTrackedEntities.Add(trackedName);
}
}
// Only the names that are not already tracked are read from the storage medium.
List<string> unresolvedNames = [.. resolvedByName.Keys.Where(name => !namesResolvedFromTrackedEntities.Contains(name))];
if (unresolvedNames.Count > 0)
{
List<TEntity> storedEntities = await context.Set<TEntity>()
.Where(entity => unresolvedNames.Contains(EF.Property<string>(entity, nameof(ISharedReferenceEntity.Name))))
.ToListAsync(cancellationToken).ConfigureAwait(false);
foreach (TEntity storedEntity in storedEntities)
resolvedByName[storedEntity.Name!] = storedEntity;
}
return resolvedByName;
}
/// <summary>
/// Maps <paramref name="incomingEntities"/> to the single resolved instance that represents each of their names.
/// </summary>
/// <typeparam name="TEntity">The type of the shared reference entity.</typeparam>
/// <param name="incomingEntities">The shared references that must be mapped to their resolved instances.</param>
/// <param name="resolvedEntities">The resolved instances, as returned by <see cref="ResolveAsync{TEntity}"/>.</param>
/// <returns>The resolved instances, without any duplicate.</returns>
internal static IReadOnlyCollection<TEntity> Normalize<TEntity>(IEnumerable<TEntity> incomingEntities, IReadOnlyDictionary<string, TEntity> resolvedEntities)
where TEntity : class, ISharedReferenceEntity
{
HashSet<TEntity> normalizedEntities = [];
foreach (TEntity incomingEntity in incomingEntities)
{
string? name = incomingEntity.Name;
if (string.IsNullOrWhiteSpace(name))
continue;
if (resolvedEntities.TryGetValue(name, out TEntity? resolvedEntity) && resolvedEntity is not null)
normalizedEntities.Add(resolvedEntity);
}
return normalizedEntities;
}
/// <summary>
/// Reconciles the shared reference collection <paramref name="existingEntities"/> against <paramref name="incomingEntities"/>, reusing the stored rows whose names already exist.
/// </summary>
/// <typeparam name="TEntity">The type of the shared reference entity.</typeparam>
/// <param name="context">The Entity Framework context the stored rows are read through.</param>
/// <param name="existingEntities">The tracked collection that is reconciled in place.</param>
/// <param name="incomingEntities">The desired shared references.</param>
/// <param name="invalidNameError">The error returned when a shared reference carries a name that is null or whitespace.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>An <see cref="Result{TValue}"/> representing either a successful operation, or an error.</returns>
internal static async Task<Result<Updated>> ReconcileAsync<TEntity>(LuminaDbContext context, ICollection<TEntity> existingEntities, IEnumerable<TEntity> incomingEntities, Error invalidNameError, CancellationToken cancellationToken)
where TEntity : class, ISharedReferenceEntity
{
List<TEntity> incomingList = [.. incomingEntities];
Result<IReadOnlyDictionary<string, TEntity>> resolveResult = await ResolveAsync(context, incomingList, invalidNameError, cancellationToken).ConfigureAwait(false);
if (resolveResult.IsFailure)
return resolveResult.Errors;
CollectionReconciler.Reconcile(
existingEntities,
Normalize(incomingList, resolveResult.Value),
existingEntity => existingEntity.Name!,
incomingEntity => incomingEntity.Name!,
shouldReplace: (existingEntity, incomingEntity) => false,
createNew: incomingEntity => incomingEntity);
return Result.Updated;
}
}
+1
View File
@@ -161,6 +161,7 @@ Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "architecture-decision-log",
..\docs\technical\architecture\architecture-knowledge-management\architecture-decision-log\architecture-decision-record-0011.md = ..\docs\technical\architecture\architecture-knowledge-management\architecture-decision-log\architecture-decision-record-0011.md
..\docs\technical\architecture\architecture-knowledge-management\architecture-decision-log\architecture-decision-record-0012.md = ..\docs\technical\architecture\architecture-knowledge-management\architecture-decision-log\architecture-decision-record-0012.md
..\docs\technical\architecture\architecture-knowledge-management\architecture-decision-log\architecture-decision-record-0013.md = ..\docs\technical\architecture\architecture-knowledge-management\architecture-decision-log\architecture-decision-record-0013.md
..\docs\technical\architecture\architecture-knowledge-management\architecture-decision-log\architecture-decision-record-0014.md = ..\docs\technical\architecture\architecture-knowledge-management\architecture-decision-log\architecture-decision-record-0014.md
EndProjectSection
EndProject
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "domain", "domain", "{3EE8EFDF-4D55-4EA3-BEE2-74D00CB50570}"