Example #1
0
        public static WorkTime Combine(WorkTime w1, WorkTime w2)
        {
            if (w1.AggregateId != w2.AggregateId)
            {
                throw new Exception("Invalid aggregate id");
            }

            if (w1.AggregateVersion == w2.AggregateVersion)
            {
                return(w1);
            }

            WorkTime v1 = w1.AggregateVersion > w2.AggregateVersion ? w2 : w1;
            WorkTime v2 = w1.AggregateVersion > w2.AggregateVersion ? w1 : w2;

            foreach (var ev in v2.PendingEvents)
            {
                if (ev.AggregateVersion > v1.AggregateVersion)
                {
                    v1.AsDynamic().Apply(ev);
                    v1.AddEvent(ev);
                }
            }

            return(v1);
        }
Example #2
0
        public static WorkTime FromEvents(IEnumerable <Event> events)
        {
            var   workTime = new WorkTime();
            Event?last     = null;

            foreach (var ev in events)
            {
                if (last == null)
                {
                    if (ev.AggregateVersion != 1)
                    {
                        throw new Exception(
                                  $"Cannot create aggregate starting from event version {ev.AggregateVersion}");
                    }

                    workTime.AggregateId = ev.AggregateId;
                }

                workTime.AsDynamic().Apply(ev);
                last = ev;
            }

            if (last == null)
            {
                throw new Exception("empty event list");
            }

            workTime.AggregateVersion = last.AggregateVersion;

            return(workTime);
        }