.netevent-sourcingeventstoredb

EventStore and EventMetadata in .net 6


When I append events to the eventstream log I'm using ...

var myEvents = events.Select(@event => new EventData(
            Guid.NewGuid(),
            @event.GetType().Name,
            true,
            Serialize(@event),
            null //metadata
        )).ToArray();

return connection.AppendToStreamAsync(streamName, version, myEvents);

Below is an example how I deserialize the event when I retrieve the event from the store, this will not work because I cannot deserialize it without metadata (which I struggle to insert, it's null cause I don't know how to insert it).

I have an extension method for deserializing ResolvedEvent from EventStore.ClientAPI.

using System.Diagnostics.Eventing.Reader
public static class EventDeserializer
{
   public static object Deserialize(this ResolvedEvent resolvedEvent)
   {
      var meta = JsonConvert.DeserializeObject<EventMetadata>
                   (Encoding.UTF8.GetString(resolvedEvent.Event.Metadata));
      var dataType = Type.GetType(meta.GetType().ToString());
      var jsonData = Encoding.UTF8.GetString(resolvedEvent.Event.Data);

      return JsonConvert.DeserializeObject(jsonData, dataType);
   }
}

if matters I'm using .net 6 and EventStore.Client 5.0.12. Just for the info, I'm able to insert the event in the store (without metadata). The issue here is when I load the event and trying to deseralize it.


Solution

  • Metadata is just a JSON object. You can serialize it the same way you do it with the event data.

    I am not sure why you use the EventMetadata type from System.Diagnostics.Eventing.Reader as it has nothing to do with the EventStoreDB client.

    You don't necessarily need to store the event type in metadata as it's already in the resolved event, the EventType property of type string.

    If you don't need event meta, you can avoid reading it. If you need the reading function to work with null meta, you can check for null.