David Silva Smith
David Silva Smith

Reputation: 11706

What do I need to do to store objects in 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?

Upvotes: 9

Views: 3331

Answers (3)

David Silva Smith
David Silva Smith

Reputation: 11706

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();
     }

Upvotes: 7

Chris Sainty
Chris Sainty

Reputation: 9306

As per our discussion in the question comments, Raven expects the objects you are storing to be regular classes, what I mean by this is they should JSON serialize to a structure of { Id:... }.

Storing a string (JSON "...") or a list (JSON [{},{}]) directly, is not going to work. Though ofcourse you can store these as properties of your document object.

Upvotes: 5

Matt Warren
Matt Warren

Reputation: 10291

Try using RavenJArray.FromObject(..) that will work with a list

Upvotes: 0

Related Questions