public void Save(Guid id, IEnumerable <IEvent> events, int expectedVersion) { var lastStoredEvent = Events .Where(e => e.Id == id) .OrderByDescending(ev => ev.Version) .FirstOrDefault(); var lastVersion = lastStoredEvent == null ? -1 : lastStoredEvent.Version; if (lastVersion != expectedVersion) { throw new ConcurrencyException(); } foreach (var @event in events) { var serializedEvent = _eventsSerializer.SerializeEvent(@event); Events.Add(new EventDescriptor { Version = @event.Version, Id = id, Data = serializedEvent.Data, Type = serializedEvent.Type }); _bus.Send(@event); } }
public void Save(AggregateRoot aggregateRoot, int expectedVersion) { var events = aggregateRoot.GetUncommittedChanges(); var lastStoredEvent = Events .Where(e => e.Id == aggregateRoot.Id) .OrderByDescending(ev => ev.Version) .FirstOrDefault(); var lastVersion = lastStoredEvent == null ? -1 : lastStoredEvent.Version; if (lastVersion != expectedVersion) { throw new ConcurrencyException(); } foreach (var @event in events) { var serializedEvent = _eventsSerializer.SerializeEvent(@event); lastVersion = @event.Version; Events.Add(new EventDescriptor { Version = @event.Version, Id = aggregateRoot.Id, Data = serializedEvent.Data, Type = serializedEvent.Type }); _bus.Send(@event); } var snapshottableAggregateRoot = aggregateRoot as SnapshottableAggregateRoot; if (snapshottableAggregateRoot != null && snapshottableAggregateRoot.ShouldCreateSnapshot()) { var snapshot = snapshottableAggregateRoot.GetSnapshot(); snapshot.Version = lastVersion; _snapshotStore.SaveSnapshot(snapshot); } }