Self-regulation frame found while serializing data models in MVC5 / EF6

I am getting this "Self Regulating Loop Detected" error when serializing using Json.NET

I have a model book

public class Book
{
    public Book()
    {
        BookPersonMap = new List<BookPersonMap>();
    }

    public int BookId { get; set; }

    public virtual ICollection<BookPersonMap> BookPersonMap { get; private set; }

    (And many other virtual Icollections)
}

      

And this is the BookPerson display class:

public class BookPersonMap
{
    public int BookId { get; set; }

    public string PersonName { get; set; }

    public int PersonTypeId { get; set; }

    public virtual Book Book { get; set; } // Foreign keys

    public virtual PersonType PersonType { get; set; }
}

      

When I try to Serialize the Book object, it throws:

"Self referencing loop detected for property 'Book' with type 'System.Data.Entity.DynamicProxies.Book_57F0FA206568374DD5A4CFF53C3B41CFDDC52DBBBA18007A896 08A96E7A783F8'. Path 'BookPersonMap[0]'."

I have tried things suggested in some similar posts Example:

  • PreserveReferencesHandling = PreserveReferencesHandling.Objects in Serializer preferences returns 3 million string!

  • ReferenceLoopHandling = ReferenceLoopHandling.Ignore in Serializer settings: "An exception of type 'System.OutOfMemoryException' occurred in Newtonsoft.Json.dll but was not handled in user code"

  • ^ Same luck with "ReferenceLoopHandling.Serialize"

  • MaxDepth = 1 : endless loop again.

Putting [JsonIgnore] on virtual properties works, but it's a tedious task (due to multiple FK references) and inefficient because if I missed one property and throw an exception.

What's missing in Json settings for them, not working?

+3


source to share


3 answers


I believe I can help you fix this issue https://code.msdn.microsoft.com/Loop-Reference-handling-in-caaffaf7#content



+1


source


Create a constructor for your controller and put this line of code on it: db.Configuration.ProxyCreationEnabled = false; // db is a context instance.



0


source


I found that the best way to solve this type of errors is to flatten your model using the view model.

Place a breakpoint on your object before serializing it and start drilling in child properties. You will probably find that you can go on and on.

This is what the serializer is choking on.

-2


source







All Articles