I am using JSON.net to serialize my EntityFramework objects.
In the past, I have created a class that applies the "JsonIgnore" attribute to a property, and then I set the "MetadataType" attribute of my main EntityFramework class to that newly created class.
Here is an example:
The class that will be applied to the EF class:
public class Role_DoNotSerialize
{
[JsonIgnore]
public string Users { get; set; }
}
The partial class file for the EF class:
[MetadataType(typeof(Role_DoNotSerialize))]
public partial class Role
{
}
In the above example, the property "Users" will not be serialized when serializing a "Role" object.
My problem is, this same technique fails to work when I add in the EntityKey property like so:
public class Role_DoNotSerialize
{
[JsonIgnore]
public string Users { get; set; }
[JsonIgnore]
public System.Data.EntityKey EntityKey { get; set; }
}
Using this class, the "EntityKey" property is still serialized. What am I doing wrong?
you can do this by implementing your own ContractResolver ( example code with JSON.NET 4.5, but also possible with older versions )
public class ExcludeEntityKeyContractResolver : DefaultContractResolver
{
protected override IList<JsonProperty> CreateProperties(Type type, MemberSerialization memberSerialization)
{
IList<JsonProperty> properties = base.CreateProperties(type,memberSerialization);
return properties.Where(p => p.PropertyType != typeof (System.Data.EntityKey)).ToList();
}
}
you can then set this to set the ContractResolver for your JsonSerializerSettings object
JsonSerializerSettings serializerSettings = new JsonSerializerSettings();
serializerSettings.ContractResolver = new ExcludeEntityKeyContractResolver();
Note that you are not limited to just that one lambda function but that you can implement any sort of checks you want. You can even override the Converter per property to do custom serialization.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With