Inną opcją jest jeszcze zapisywanie sobie takich informacji w eventach i zapisywanie streamu tych eventów jako audit log, co ja osobiście preferuję. O tak:
public interface IEvent
{
Guid Id { get; }
int EntityId { get; }
}
public class EntityCreated : IEvent
{
public EntityCreated(int entityId, int creatorId)
{
Id = Guid.NewGuid();
EntityId = entityId;
CreatedAt = DateTime.UtcNow;
CreatedBy = creatorId;
}
public Guid Id { get; }
public int EntityId { get; }
public DateTime CreatedAt { get; }
public int CreatedBy { get; }
}
public class EntityModified : IEvent
{
public EntityModified(int entityId, string fieldName, string oldValue, string newValue, int modifierId)
{
Id = Guid.NewGuid();
EntityId = entityId;
FieldName = fieldName;
OldValue = oldValue;
NewValue = newValue;
ModifiedAt = DateTime.UtcNow;
ModifiedBy = modifierId;
}
public Guid Id { get; }
public int EntityId { get; }
public string FieldName { get; }
public string OldValue { get; }
public string NewValue { get; }
public DateTime ModifiedAt { get; }
public int ModifiedBy { get; }
}
public abstract class EntityBase
{
private readonly List<IEvent> _events = new List<IEvent>();
public int Id { get; }
public IReadOnlyCollection<IEvent> Events => _events;
public void RegisterEvent(IEvent @event)
{
_events.Add(@event);
}
public void ClearEvents()
{
_events.Clear();
}
}
public class Entity : EntityBase
{
private Entity(int creatorId)
{
RegisterEvent(new EntityCreated(Id, creatorId));
}
public string Name { get; private set; }
public static Entity Create(int creatorId) => new(creatorId);
public void ChangeName(string newName, int modifierId)
{
RegisterEvent(new EntityModified(Id, nameof(Name), Name, newName, modifierId));
Name = newName;
}
}
public class Repository<TEntity> where TEntity : Entity
{
public void Save(TEntity entity)
{
// insert entity and its events in one transaction
entity.ClearEvents(); // after commit
}
}
Oczywiście to tylko przykład, żeby pokazać kierunek. Konretna implementacja będzie się różnić w zależności od wymagań takiego audit loga i modelu dziedziny.