private IEventSourcedAggregateRoot ConstructAndLoadEntityFromEvents(Guid aggregateId, IReadOnlyDictionary <string, string> eventStreamMetadata, IReadOnlyCollection <IEventStoreRecord> eventRecords) { int version = (int)(eventRecords.LastOrDefault()?.StreamSequenceNumber ?? 0); var events = eventRecords.Select(x => x.Event as DomainAggregateEvent ?? throw new InvalidOperationException( $"Cannot load event sourced aggregate ID {aggregateId}: event stream contains non-DomainAggregateEvent events of type {x.Event.GetType().FullName}")) .ToList(); AggregateState state = new AggregateState(version, events); if (!eventStreamMetadata.TryGetValue(AggregateEventStreamMetadataNames.ClassId, out string classIdString)) { throw new InvalidOperationException($"Cannot load event sourced aggregate ID {aggregateId}: aggregate class ID not found in event stream metadata"); } Guid classId = Guid.Parse(classIdString); Type entityType = entityTypeManager.GetClassInfoByClassId(classId).ClrType; IEventSourcedAggregateRoot aggregate = (IEventSourcedAggregateRoot)ConstructEntity(entityType, aggregateId); aggregate.LoadState(state); return(aggregate); }
public IEventSourcedAggregateRoot ConstructAndLoadEntityFromEvents(Guid aggregateId, IReadOnlyDictionary <string, string> eventStreamMetadata, IReadOnlyCollection <IEventStoreRecord> eventRecords) { if (!eventStreamMetadata.TryGetValue(AggregateEventStreamMetadataNames.ClassId, out string classIdString)) { throw new InvalidOperationException($"Cannot load event sourced aggregate ID {aggregateId}: aggregate class ID not found in event stream metadata"); } Guid classId = Guid.Parse(classIdString); Type entityType = entityTypeManager.GetClassInfoByClassId(classId).ClrType; IEnumerable <IEventMessage <DomainAggregateEvent> > eventMessages; try { eventMessages = eventRecords.Select(EventStoreEventMessage.FromRecord) .Cast <IEventMessage <DomainAggregateEvent> >(); } catch (InvalidCastException e) { throw new InvalidOperationException( $"Cannot load event sourced aggregate ID {aggregateId}: event stream contains non-DomainAggregateEvent events", e); } var upgradedEvents = eventStreamUpgrader.UpgradeStream(eventMessages, eventStreamMetadata); var events = upgradedEvents.Select(x => x.Event).ToArray(); int version = (int)(eventRecords.LastOrDefault()?.AdditionalMetadata.GetAggregateVersion() // use non-upgraded event records to preserve the versions ?? eventRecords.LastOrDefault()?.StreamSequenceNumber ?? 0); AggregateState state = new AggregateState(version, events); IEventSourcedAggregateRoot aggregate = (IEventSourcedAggregateRoot)ConstructEntity(entityType, aggregateId); aggregate.LoadState(state); return(aggregate); }