public void SaveEventsFor <TAggregate>(Guid?id, int eventsLoaded, IEnumerable <Event> newEvents) { if (!id.HasValue) { throw new ArgumentException("Why no id?"); } var events = new List <EventData>(); foreach (var newEvent in newEvents) { var eventBytes = BytesToString.ToBytes(JsonConvert.SerializeObject(newEvent, new JsonSerializerSettings() { TypeNameHandling = TypeNameHandling.All })); var typeMeta = BytesToString.ToBytes(JsonConvert.SerializeObject(newEvent.GetType(), new JsonSerializerSettings() { TypeNameHandling = TypeNameHandling.All })); events.Add(new EventData(Guid.NewGuid(), aggregateStreamName, true, eventBytes, typeMeta)); } esConnection.AppendToStream(GetStreamName <TAggregate>(id.Value), eventsLoaded, events); }
public void Save(IAggregate aggregate, Guid commitId, Action <IDictionary <string, object> > updateHeaders) { var commitHeaders = new Dictionary <string, object> { { CommitIdHeader, commitId }, { AggregateClrTypeHeader, aggregate.GetType().AssemblyQualifiedName } }; updateHeaders(commitHeaders); var streamName = _aggregateIdToStreamName(aggregate.GetType(), aggregate.Id); var newEvents = aggregate.GetUncommittedEvents().Cast <object>().ToList(); var originalVersion = aggregate.Version - newEvents.Count; var expectedVersion = originalVersion == 0 ? ExpectedVersion.NoStream : originalVersion; var eventsToSave = newEvents.Select(e => ToEventData(Guid.NewGuid(), e, commitHeaders)).ToList(); if (eventsToSave.Count < WritePageSize) { _eventStoreConnection.AppendToStream(streamName, expectedVersion, eventsToSave); } else { var transaction = _eventStoreConnection.StartTransaction(streamName, expectedVersion); var position = 0; while (position < eventsToSave.Count) { var pageEvents = eventsToSave.Skip(position).Take(WritePageSize); transaction.Write(pageEvents); position += WritePageSize; } transaction.Commit(); } aggregate.ClearUncommittedEvents(); }