public void Extrapolate(IEvent @event) { var events = _eventStream.Where(e => e.Kind == EventKinds.AnimalIntoMob).ToList(); var subjects = events.Select(e => e.Subject).Distinct(); _store.Clear(); foreach (var sub in subjects) { var subjectEvents = events.Where(e => e.Subject == sub) .Select(e => JsonConvert.DeserializeObject <AnimalIntoMobObservation>(e.Data)) .OrderBy(o => o.Observed); AnimalMobHistory previous = null; foreach (var subEvent in subjectEvents) { if (previous == null) { previous = new AnimalMobHistory() { AnimalId = subEvent.AnimalId, MobId = subEvent.MobId, DateIn = subEvent.Observed }; _store.Add(previous); continue; } var current = new AnimalMobHistory() { AnimalId = subEvent.AnimalId, MobId = subEvent.MobId, DateIn = subEvent.Observed }; previous.DateOut = subEvent.Observed; _store.Add(current); } var latest = DataStore.DataStore.AnimalMobHistories.Where(h => h.AnimalId == sub) .OrderByDescending(h => h.DateIn).FirstOrDefault(); if (latest == null) { continue; } var animal = DataStore.DataStore.Animals.First(a => a.Id == latest.AnimalId); animal.MobId = latest.MobId; DataStore.DataStore.Animals.Update(animal); } }
private TAggregateRootState CreateState(IEventStream stream) { Contract.Requires(stream != null); Contract.Ensures(Contract.Result <TAggregateRootState>() != null); var snapshotRevision = stream.FirstOrDefault(x => x is SnapshotRevision) as SnapshotRevision; // order domain events and flatten list IReadOnlyCollection <IDomainEvent> domainEvents = stream.Where(x => x is DomainEventRevision) .OrderBy(x => x.Version) .Cast <DomainEventRevision>() .SelectMany(x => x.DomainEvents) .ToList(); var domainEventsExist = domainEvents.Any(); TAggregateRootState state; // check for valid stream if (snapshotRevision == null) { if (domainEventsExist) { // domain events only state = _aggregateRootStateBuilder.Build(domainEvents); } else { throw new InvalidOperationException("Event stream does not contain a snapshot or domain event revision."); } } else { if (domainEventsExist) { // snapshot and domain events state = _aggregateRootStateBuilder.Build(snapshotRevision.Snapshot.Data, domainEvents); } else { // snapshot only state = _aggregateRootStateBuilder.Build(snapshotRevision.Snapshot.Data); } } Contract.Assume(state != null); return(state); }