Search code examples
c#nosqlravendbdocument-database

RavenDB and Composite pattern


Let say I have such structure

public class Form
{
   public List<Field> Fields { get; set; }
}

The Field class can be composite and include other Fields derived from the Field class as well, so I have some sort of hierarchical structure. The Form is persisted into RavenDB as solid document and it works ok. I am just wondering about getting Form instance back from RavenDB, I want Raven to create appropriate classes (classes, which are derived from Field class). So let's say if I have two derived classes FieldDerived1 and FieldDerived2 and put them into the Fields collection of the Form after getting them back I want have two elements with actual types - FieldDerived1 and FieldDerived2 with all additional properties I added to these classes?


Solution

  • It will work just fine. Raven uses Json.Net for it's serialization, which will add a $type property to your data so it can be properly deserialized to the correct type.

    Assuming your fields look something like this:

    public class Field
    {
      public string Name {get; set;}
    }
    
    public class FieldDerived1 : Field
    {
      public int Length {get; set;}
    }
    
    public class FieldDerived2 : Field
    {
      public string Color {get; set;}
    }
    

    Raven will store the Form class like this:

    {
      Fields: [
        {
          "$type": "YourNamespace.FieldDerived1, YourAssembly",
          "Name": "foo",
          "Length": 10
        },
        {
          "$type": "YourNamespace.FieldDerived2, YourAssembly",
          "Name": "bar",
          "Color": "blue"
        }
      ]
    }