8

I have a property I don't want to store in RavenDB. If I add the JsonIgnore attribute RavenDB will ignore fine but then so will WebApi. I still want WebApi to serialize the data down to a web client though.

How do I tell RavenDB to ignore a property but still have WebApi serialize it?

j0k
  • 22,600
  • 28
  • 79
  • 90
kareem
  • 753
  • 1
  • 5
  • 10

1 Answers1

14

In RavenDB 2.0

using Raven.Imports.Newtonsoft.Json

public class Foo
{
    [JsonIgnore]
    public string Bar { get; set; }
}

Because it's using raven's internalized copy of json.net - WebApi won't pick up the attribute.

In RavenDB 1.0 or 2.0

You can customize the json serialization of your object directly using a custom json contract resolver.

public class CustomContractResolver : DefaultRavenContractResolver
{
    public CustomContractResolver(bool shareCache) : base(shareCache)
    {
    }

    protected override List<MemberInfo> GetSerializableMembers(Type objectType)
    {
        var members = base.GetSerializableMembers(objectType);

        if (objectType == typeof(Foo))
            members.RemoveAll(x => x.Name == "Baz");

        return members;
    }
}

Wire it up to your document store at time of initialization:

documentStore.Conventions.JsonContractResolver = new CustomContractResolver(true);
documentStore.Initialize();

Because it's not wired up anywhere else, it will only affect RavenDB. Customize it however you like to suit your needs.

Matt Johnson-Pint
  • 230,703
  • 74
  • 448
  • 575
  • [Raven.Imports.Newtonsoft.Json.JsonIgnore] alone did the trick. I can now control which properties are serialized to RavenDB separately from WebAPI. What's the need/benefit of the second part of this answer? – kareem Jan 06 '13 at 07:27
  • 2
    Raven 1.0 is still out there. And many people don't like polluting their entities with attributes. – Matt Johnson-Pint Jan 06 '13 at 07:42
  • Thanks, the contract resolver saved me having to actually employ good software architecture ;) – Jeff Aug 01 '13 at 15:22