astral-api/Astral.Services/Helpers/EntityHelpers.cs
Mike d84d7631ce
All checks were successful
ci/woodpecker/push/woodpecker Pipeline was successful
ci/woodpecker/pr/woodpecker Pipeline was successful
ci/woodpecker/pull_request_closed/woodpecker Pipeline was successful
Call user presence
2024-12-15 20:20:27 +00:00

37 lines
1.3 KiB
C#

// <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;
}
}