RavenDB IRavenQueryable understanding types (Event Sourcing)

172 Views Asked by At

I'm currently building a repository in conjunction with RavenDB that is used specifically for Event Sourcing. (Storing Events).

I have wrote code that allows me to pull out the events, based on there type.

It's working, but its not a great implementation as I'm using IEnumerable rather than IQueryable. I'm struggling to implement this as an IRavenQueryable, as the Type checking isn't allowed.

My Question is purely, is there a better way to achieve this?

Below is my code.

I have an Interface that all Event objects adhere too.

public interface IEvent
    {
        string Id { get; set; }
        Guid AggregateRootId { get; set; }
        int Version { get; set; }
        DateTime DateCreated { get; set; }

    }

Next I have my event classes (These are just Test Classes) :-

public class BookDecriptionChangedEvent : IEvent
    {
        public string Id { get; set; }
        public Guid AggregateRootId { get; set; }
        public string Description { get; set; }
        public int Version { get; set; }
        public DateTime DateCreated { get; set; }
    }

 public class BookTitleChangedEvent : IEvent
    {
        public string Id { get; set; }
        public Guid AggregateRootId { get; set; }
        public string Name { get; set; }
        public int Version { get; set; }
        public DateTime DateCreated { get; set; }
    }

For my Repository I want to create a Method that Allows me to Get All Events by AggregateRoodId. But I want to be able to pass in the many different types of event like this :-

// Get All Events for this Aggregate.
_repository.GetByAggreageRootId<IEvent>("b876baea-f2c2-49e1-9abc-683e031cf6d4");

// Get All Events of Type BookDecriptionChangedEvent for this Aggregate.
_repository.GetByAggreageRootId<BookDecriptionChangedEvent>("b876baea-f2c2-49e1-9abc-683e031cf6d4");

// Get All Events of Type BookTitleChangedEvent for this Aggregate.
_repository.GetByAggreageRootId<BookTitleChangedEvent>("b876baea-f2c2-49e1-9abc-683e031cf6d4");

Currently I have achieved this by writing the following repository code :-

 public interface IRepository
    {
        IEnumerable<IEvent> GetByAggreageRootId<TEvent>(string id) where TEvent : IEvent;
    }

In the Implementation I have this Method :-

public IEnumerable<IEvent> GetByAggreageRootId<TEvent>(string id) where TEvent : IEvent
        {
            if (Session == null)
            {
                throw new ArgumentException("Document Session");
            }

            using (Session)
            {
                if (typeof(TEvent) == typeof(IEvent))
                {
                    return GetAll<IEvent>().Where(p => p.AggregateRootId == new Guid(id));
                }

                return GetAll<IEvent>().ToList().Where(p => p.GetType() == typeof (TEvent) && p.AggregateRootId == new Guid(id));
            }

}

0

There are 0 best solutions below