Created
January 13, 2021 20:22
-
-
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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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