#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.DataAccess.Entities.Common;
using Lumina.DataAccess.Core.UoW;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.ChangeTracking;
using Microsoft.EntityFrameworkCore.Metadata;
using System.Collections.Generic;
using System.Linq;
#endregion
namespace Lumina.DataAccess.Common.Persistence;
///
/// 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.
///
internal static class EditableValuesCopier
{
///
/// Copies the scalar values of onto the 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.
///
///
/// 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.
///
/// The type of the tracked and mapped repository entity.
/// The Entity Framework context that tracks .
/// The tracked entity whose editable values are updated.
/// The mapped entity carrying the desired values.
public static void CopyEditableValues(LuminaDbContext context, TEntity tracked, TEntity incoming) where TEntity : class, IAuditableEntity
{
EntityEntry trackedEntry = context.Entry(tracked);
EntityEntry 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 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;
}
}
}