18

I have a document model to store in RavenDB but I don't want to store a calculated property. How do I tell RavenDB to ignore this property?

In the below example I don't want to store Duration.

public class Build
{
    public string Id { get; set; }
    public string Name { get; set; }
    public DateTime StartedAt { get; set; }
    public DateTime FinishedAt { get; set; }

    public TimeSpan Duration { get { return StartedAt.Subtract(FinishedAt); }}
}
Adam Spicer
  • 2,703
  • 25
  • 37
Ben Clark-Robinson
  • 1,449
  • 16
  • 22

1 Answers1

27

Just decorate the Duration property with [JsonIgnore] like this:

public class Build
{
    public string Id { get; set; }
    public string Name { get; set; }
    public DateTime StartedAt { get; set; }
    public DateTime FinishedAt { get; set; }

    [Raven.Imports.Newtonsoft.Json.JsonIgnore]
    //[Newtonsoft.Json.JsonIgnore] // for RavenDB 3 and up
    public TimeSpan Duration { get { return StartedAt.Subtract(FinishedAt); }}
}

See more here: http://ravendb.net/docs/client-api/advanced/custom-serialization

AndreasHassing
  • 687
  • 4
  • 19
Adam Spicer
  • 2,703
  • 25
  • 37
  • 1
    Side note: If this class is in -another- project (eg. AwesomeNamespace.Core), then this other project needs to either nuget package Newtonsoft.Json or RavenDb.Client. Basically, this attribute is from the Newtonsoft.Json library. This could change in the future, but at the time of me writing this comment .. that's the score. – Pure.Krome May 04 '12 at 03:42
  • 9
    "With version 2 of RavenDB you need to use the attributes from the Raven.Imports.Newtonsoft.Json namespace instead of the Newtonsoft.Json namespace. The Newtonsoft.Json namespacewill be ignored." -- Taken from the comments on the above linked post. – ChadT Aug 08 '13 at 02:03
  • 2
    RavenDB 3: Use `[Newtonsoft.Json.JsonIgnore]` rather than `Raven.Imports.Newtonsoft.Json` namespace. Seems, they have changed it since @ChadT's commented on v2. – Alex Klaus Oct 31 '17 at 00:57