38 lines
1.3 KiB
C#
38 lines
1.3 KiB
C#
namespace Prefab.Domain.Common;
|
|
|
|
/// <summary>
|
|
/// Base implementation for aggregate entities that support domain events.
|
|
/// </summary>
|
|
/// <typeparam name="T">Entity identifier type.</typeparam>
|
|
public abstract class Entity<T> : IEntity<T>, IHasDomainEvents
|
|
{
|
|
private readonly List<Event> _events = [];
|
|
|
|
/// <inheritdoc />
|
|
public T Id { get; set; } = default!;
|
|
|
|
/// <inheritdoc />
|
|
public IReadOnlyCollection<Event> Events => _events.AsReadOnly();
|
|
|
|
/// <inheritdoc />
|
|
public void AddEvent(Event e) => _events.Add(e);
|
|
|
|
/// <inheritdoc />
|
|
public void RemoveEvent(Event e) => _events.Remove(e);
|
|
|
|
/// <inheritdoc />
|
|
public void ClearEvents() => _events.Clear();
|
|
|
|
/// <summary>
|
|
/// Generates a UUIDv7 identifier using the supplied timestamp, primarily for testing scenarios.
|
|
/// </summary>
|
|
/// <param name="timestamp">The timestamp used to seed the UUID generator.</param>
|
|
/// <exception cref="InvalidOperationException">Thrown when the entity identifier type is not <see cref="Guid"/>.</exception>
|
|
protected void GenerateIdWithTimestamp(DateTime timestamp)
|
|
{
|
|
Id = typeof(T) == typeof(Guid)
|
|
? (T)(object)Guid.CreateVersion7(timestamp)
|
|
: throw new InvalidOperationException("Cannot generate a UUIDv7 for a non-Guid entity.");
|
|
}
|
|
}
|