Skip to content

Instantly share code, notes, and snippets.

@jlewin
Created January 13, 2021 20:22
Show Gist options
  • Save jlewin/b1b572f4a34515a6a63d78475a316716 to your computer and use it in GitHub Desktop.
Save jlewin/b1b572f4a34515a6a63d78475a316716 to your computer and use it in GitHub Desktop.
Serialize EF dbset - quickly adapt action method to dump dbset to json without serializing virtual navigation props
// As described in https://stackoverflow.com/q/26162902/84369
public ActionResult Index()
{
var sketches = db.Sketches.Include(p => p.Board);
// Serializer settings
var settings = new JsonSerializerSettings
{
ContractResolver = new CustomResolver(),
PreserveReferencesHandling = PreserveReferencesHandling.None,
ReferenceLoopHandling = ReferenceLoopHandling.Ignore,
Formatting = Formatting.Indented
};
var json = Newtonsoft.Json.JsonConvert.SerializeObject(sketches, settings);
System.IO.File.WriteAllText(@"c:\temp\sketches.json", json);
return View(sketches.ToList());
}
public class CustomResolver : DefaultContractResolver
{
public CustomResolver() { }
protected override JsonProperty CreateProperty(MemberInfo member, MemberSerialization memberSerialization)
{
JsonProperty prop = base.CreateProperty(member, memberSerialization);
var propInfo = member as PropertyInfo;
if (propInfo != null)
{
if (propInfo.GetMethod.IsVirtual && !propInfo.GetMethod.IsFinal)
{
prop.ShouldSerialize = obj => false;
}
}
return prop;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment