1

I have read a lot about this type of error :

"A circular reference was detected while serializing an object of type ..." But I could not found a solution to it when it happens in ASP.Net MVC Kendo Grid Action Method. I have the following action method and I want to insert into another related table at the same time :

[AcceptVerbs(HttpVerbs.Post)]
        public ActionResult SeasonTradeCreate([DataSourceRequest] DataSourceRequest request, [Bind(Prefix = "models")] IEnumerable<BKP_STRADE> models, decimal? DOC_SEQ)
        {
            if (models.Any())
            {
                foreach (BKP_STRADE modelItem in models)
                {
                    Db.BKP_STRADE.Add(modelItem);
                    BKP_STRADE_ROW BKP_STRADE_ROW_OBJ = new BKP_STRADE_ROW();
                    BKP_STRADE_ROW_OBJ.BSTR_BSTR_SEQ = modelItem.BSTR_SEQ;
                    BKP_STRADE_ROW_OBJ.DOC_SEQ = DOC_SEQ;
                    Db.BKP_STRADE_ROW.Add(BKP_STRADE_ROW_OBJ);
                }
                Db.SaveChanges();
            }
            return Json(models.ToDataSourceResult(request, ModelState));
        }

The thing is that it inserts into both table correctly but I get the following error as well after the operation :

"A circular reference was detected while serializing an object of type 'Tpph.Models.BKP_STRADE'."

Ali Roshanbin
  • 175
  • 1
  • 15
  • This means one of the entities in BKP_STRADE collection references itself. The default settings for the JS serializer cannot handle that. See https://stackoverflow.com/questions/1153385/a-circular-reference-was-detected-while-serializing-an-object-of-type-subsonic for more info. – Alaa Masoud Jul 17 '17 at 05:47
  • So what can I do ? I just want to insert into two related entities in calling the create action method of the kendo grid. how can I do it ? – Ali Roshanbin Jul 17 '17 at 05:55
  • @AliRoshanbin: Instead of linking the **objects** to eachother, try storing only their **ID**. The serializer is trying to serialize your entire object, but it gets stuck in an infinite loop as it tries to serialize `myObj1`, `myObj1.RelatedObj2`, `myObj1.RelatedObj2.RelatedObj1`, `myObj1.RelatedObj2.RelatedObj1.RelatedObj2`, and so on... – Flater Jul 17 '17 at 07:39
  • @Flater : Can you please write your suggested piece of code that can handle it ? So I can get the idea. – Ali Roshanbin Jul 18 '17 at 04:37

1 Answers1

0

Can you change

return Json(models.ToDataSourceResult(request, ModelState));

with this

return Json(new[] { models }.ToDataSourceResult(request, ModelState));