Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I tell RavenDB to ignore a property but not WebAPI?

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?

like image 309
kareem Avatar asked Jan 06 '13 03:01

kareem


1 Answers

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.

like image 147
Matt Johnson-Pint Avatar answered Nov 12 '22 00:11

Matt Johnson-Pint