Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What do I need to do to store objects in RavenDB?

Tags:

ravendb

I'm using ravendb to serialize an object and test it through mstest.

I am getting this result: System.ArgumentException: Object serialized to String. RavenJObject instance expected.

Here is my code

public class Store
{
    private static IDocumentStore store = createStore();

    private static EmbeddableDocumentStore createStore()
    {
        var returnStore = new EmbeddableDocumentStore();
        returnStore.DataDirectory = @"./PersistedData";
        returnStore.Initialize();
        return returnStore;
    }

    public static void Write(string value)
    {
        using (var session = store.OpenSession())
        {
            session.Store(value);
            session.SaveChanges();
        }
    }
}

It seems the root cause is in how RavenJObject works as this throws the same error:

RavenJObject storeMe = RavenJObject.FromObject("errors", new JsonSerializer());

How do I do custom serialization in RavenDB?

like image 447
David Silva Smith Avatar asked Feb 03 '23 16:02

David Silva Smith


1 Answers

To do custom serialization with a class you didn't write (so you can't attribute) implement Newtonsoft.Json.JsonConverter

Then register it like this:

using (var session = store.OpenSession())
     {
         session.Advanced.Conventions.CustomizeJsonSerializer = serializer => serializer.Converters.Add(MailAddressJsonConverter.Instance);
         session.Store(mailAddress);
         session.SaveChanges();
     }
like image 126
David Silva Smith Avatar answered Apr 10 '23 17:04

David Silva Smith