JSON.NET Error Self referencing loop detected for type

后端 未结 25 3487
我在风中等你
我在风中等你 2020-11-22 02:16

I tried to serialize POCO class that was automatically generated from Entity Data Model .edmx and when I used

JsonConvert.SerializeObject 

25条回答
  •  忘掉有多难
    2020-11-22 02:27

    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?

提交回复
热议问题