Skip to content

Storage Engine: Entity Framework 6

Tomas Lycken edited this page Oct 30, 2017 · 4 revisions

Most of the work is already done for you, but there are a few things you'll have to do yourself in order to use RdbmsEventStore with Entity Framework 6.

Create an IPersistedEvent implementation for your data model

In addition to the IEvent<TStreamId> interface and its default implementation Event<TStreamId>, which had a Type and an object representing your event payload, you also need an implementation of IPersistedEvent<TId, TStreamId>, which instead has a string and a byte[], representing the serialized payload. The generic type parameter TId in IPersistedEvent<TId, TStreamId> indicates the primary key type in the table where you'll store your events.

There is a default implementation EntityFrameworkEvent<TId, TStreamId> in the library, but since EF6 doesn't support generic entity types, you must create a non-generic subclass for it:

public class YourPersistedEvent : EntityFrameworkEvent<Guid, string> { } // or Event<long, long>, etc

The id types can be the same or not, it's entirely up to you. If you want to add metadata, such as the user id of the user who triggered the event, you have to create child types including that data.

Create a DbContext implementation with a DbSet<YourPersistedEvent>

This can also inherit directly from the built-in EventStoreContext<TEvent>:

public class YourEventStoreContext : EventStoreContext<YourPersistedEvent>
{
    public YourEventStoreContext() : base("name=NameOfYourConnectionString") { }
}

The constructor parameter is just passed along to the underlying DbContext. You can of course add other constructors if you need it for e.g. your design-time tooling; this variant at least works with EF Migrations.

Create the auxiliary types (or use the defaults)

The EntityFrameworkEventStore needs a couple of auxiliary types to function. If you're not customizing your event, you can use the default implementations of all of these, but if not, read more on each respective page.

Create event store instance

Usually you'll let your DI container handle this, but here's a raw sample so you know what you need.

var eventRegistry = new AssemblyEventRegistry(typeof(SomeEventPayload));
var serializer = new DefaultEventSerializer<string, Event<string>, YourPersistedEvent>(eventRegistry);

var eventFactory = new DefaultEventFactory<Guid, string, YourEvent>();
var writeLock = new WriteLock();

var context = new YourEventStoreContext();
var eventStore = new EntityFrameworkEventStore<Guid, string, YourEventStoreContext, Event<string>, IEventMetadata<string>, YourPersistendEvent>(
    context,
    eventFactory,
    writeLock,
    serializer);