RavenDb: Force Serialization of Declared Type not inherited type assigned to Collection

Viewed 17

I have the following ContractResolver that works for properties to ensure that a property is serialized to RavenDb as the declared type of the property, not the actual inherited type of the object assigned. This works well for when you want to store a reference to something else in the database that has a subset of fields but not store the entire object, but you set the property using the entire object.

public class StrictTypeContractResolver : DefaultContractResolver
{
    private readonly FieldInfo _IsSealedField = typeof(JsonContract).GetField("IsSealed", BindingFlags.Instance | BindingFlags.NonPublic)!;

    public override JsonContract ResolveContract(Type type)
    {
        var resolveContract = base.ResolveContract(type);
        _IsSealedField.SetValue(resolveContract, true);
        return resolveContract;
    }
}

The problem occurs when you have an ICollection or IList or any type of collection that you're adding objects to with the same reference and then object that inherits from reference. How do I get the Icollection to only serialize the defined type of the collection or list instead of the objects assigned?

0 Answers
Related