I tried to serialize POCO class that was automatically generated from Entity Data Model .edmx and when I used
JsonConvert.SerializeObject
I've inherited a database application that serves up the data model to the web page. Serialization by default will attempt to traverse the entire model tree and most of the answers here are a good start on how to prevent that.
One option that has not been explored is using interfaces to help. I'll steal from an earlier example:
public partial class CompanyUser
{
public int Id { get; set; }
public int CompanyId { get; set; }
public int UserId { get; set; }
public virtual Company Company { get; set; }
public virtual User User { get; set; }
}
public interface IgnoreUser
{
[JsonIgnore]
User User { get; set; }
}
public interface IgnoreCompany
{
[JsonIgnore]
User User { get; set; }
}
public partial class CompanyUser : IgnoreUser, IgnoreCompany
{
}
No Json settings get harmed in the above solution. Setting the LazyLoadingEnabled and or the ProxyCreationEnabled to false impacts all your back end coding and prevents some of the true benefits of an ORM tool. Depending on your application the LazyLoading/ProxyCreation settings can prevent the navigation properties loading without manually loading them.
Here is a much, much better solution to prevent navigation properties from serializing and it uses standard json functionality: How can I do JSON serializer ignore navigation properties?