0

The following JsonResult returns:

A circular reference was detected while serializing an object of type 'System.Data.Entity.DynamicProxies.IntegerList_76C57D0878505062AEA67E9EB9F708830FA20FDE4F13A53543EC2E6ED84C1A2C'

and according to the debugger

'Children could not be evaluated'

for the line

var integerLists = db.IntegerLists.Include("Integers");

If I remove the include, this runs successfully. Likewise if I execute the commented code instead.

In the past, I've solved circular references by decorating my domain models with [IgnoreDataMember] but that doesn't seem to be working this time.

Controller

    public JsonResult GetIntegerLists()
    {
        var integerLists = db.IntegerLists.Include("Integers");

        //var integerLists = new List<IntegerList>();
        //integerLists.Add(new IntegerList()
        //{
        //    IntegerListID = 1,
        //    Direction = "Ascending",
        //    Performance = 467,
        //    Integers = { new Integer { IntegerValue = 34 }, new Integer { IntegerValue = 5654 }, new Integer { IntegerValue = 343 } }
        //});
        //integerLists.Add(new IntegerList()
        //{
        //    IntegerListID = 2,
        //    Direction = "Ascending",
        //    Performance = 637,
        //    Integers = { new Integer { IntegerValue = 4 }, new Integer { IntegerValue = 646 }, new Integer { IntegerValue = 23 } }
        //});
        //integerLists.Add(new IntegerList()
        //{
        //    IntegerListID = 3,
        //    Direction = "Ascending",
        //    Performance = 235,
        //    Integers = { new Integer { IntegerValue = 64378 }, new Integer { IntegerValue = 1 }, new Integer { IntegerValue = 533 } }
        //});

        return Json(integerLists, JsonRequestBehavior.AllowGet);
    }

    [HttpPost]
    public ActionResult Index(IntegerList viewModel)
    {
        if (ModelState.IsValid)
        {
            db.IntegerLists.Add(viewModel);
            db.SaveChanges();
        }

        return View();
    }

Models

public class Integer
{
    public int IntegerID { get; set; }
    public int IntegerValue { get; set; }
    public int IntegerListID { get; set; }
    public virtual IntegerList IntegerList { get; set; }
}

public class IntegerList
{
    public int IntegerListID { get; set; }
    public string Direction { get; set; }
    public long Performance { get; set; }
    public virtual ICollection<Integer> Integers { get; set; }
}
user1405195
  • 1,667
  • 4
  • 22
  • 35

1 Answers1

0

You have a navigation property back to the list it belongs to. You probably don't want to use that when serializing. Use the ScriptIgnore attribute.

public class Integer
{
    public int IntegerID { get; set; }
    public int IntegerValue { get; set; }
    public int IntegerListID { get; set; }
    [ScriptIgnore]
    public virtual IntegerList IntegerList { get; set; }
}
Michael Dunlap
  • 4,300
  • 25
  • 36