astral-api/Astral.Services/Helpers/EntityHelpers.cs

38 lines
1.3 KiB
C#
Raw Normal View History

2024-12-15 21:20:27 +01:00
// <copyright file="EntityHelpers.cs" company="alveus.dev">
// Copyright (c) alveus.dev. All rights reserved. Licensed under the MIT License.
// </copyright>
namespace Astral.Services.Helpers;
/// <summary>
/// Entity helpers.
/// </summary>
public static class EntityHelpers
{
/// <summary>
/// Apply changes only when new entity property is different and not null.
/// </summary>
/// <param name="oldEntity">Old entity to compare against.</param>
/// <param name="newEntity">New entity with new values.</param>
/// <typeparam name="TEntity">The type of entity to compare.</typeparam>
/// <returns>The new entity with changes applied.</returns>
public static TEntity ApplyChanges<TEntity>(TEntity oldEntity, TEntity newEntity)
{
var entityType = typeof(TEntity);
var properties = entityType.GetProperties();
foreach (var property in properties)
{
if (property.GetValue(newEntity) != null && property.GetValue(newEntity) != property.GetValue(oldEntity))
{
property.SetValue(oldEntity, property.GetValue(newEntity));
}
else
{
property.SetValue(oldEntity, property.GetValue(oldEntity));
}
}
return oldEntity;
}
}