Entity to json error - A circular reference was detected while serializing an object of type

前端 未结 5 982
醉梦人生
醉梦人生 2021-01-02 02:22

Following error occurred when trying to convert entity object into JSON String. I\'m using C# MVC4 with code first DB designing. It seams its because FKs and relationships b

相关标签:
5条回答
  • 2021-01-02 02:29

    it is trying to load child objects and it may be creating some circular loop property that will never end.

    also you use [ScriptIgnore] , will not serialize the public property or public field look at this :

       public class BookingHotel : IntBaseEntity            
        {    
            public string BookingName { get; set; }    
            public string BookingReference { get; set; }    
            public DateTime? CheckInDate { get; set; }    
            public DateTime? CheckOutDate { get; set; }    
            public int HotelId { get; set; }    
            [ScriptIgnore]    
            public Hotel Hotel { get; set; }        
         }         
    
    0 讨论(0)
  • 2021-01-02 02:31

    Its because it is trying to load child objects and it may be creating some circular loop that will never ending( a=>b, b=>c, c=>d, d=>a)

    you can turn it off only for that particular moment as following.So dbcontext will not load customers child objects unless Include method is called on your object

      db.Configuration.ProxyCreationEnabled = false;
      User ma = db.user.First(x => x.u_id == id);
      return Json(ma, JsonRequestBehavior.AllowGet);
    
    0 讨论(0)
  • 2021-01-02 02:34

    Why not create a class to hold the query contents? That worked for me

    0 讨论(0)
  • 2021-01-02 02:34

    I was having the same issue, what I have done is have passed only needed column to view , In my my case. only 2.

    List<SubCategory> lstSubCategory = GetSubCateroy() // list from repo
    
     var subCategoryToReturn = lstSubCategory.Select(S => new { Id  = S.Id, Name = S.Name }); 
    
    return this.Json(subCategoryToReturn , JsonRequestBehavior.AllowGet);
    

    Circular reference detected exception while serializing object to JSON

    0 讨论(0)
  • 2021-01-02 02:40

    My problem is solved by using this :

    //initialize model db
    testdbEntities dc = new testdbEntities();
    //get employee details 
    List<Employee1> lst = dc.Employee1.ToList(); 
    //selecting the desired columns
    var subCategoryToReturn = lst.Select(S => new {
        Employee_Id = S.Employee_Id,
        First_Name = S.First_Name,
        Last_Name = S.Last_Name,
        Manager_Id = S.Manager_Id
    });
    //returning JSON
    return this.Json(subCategoryToReturn , JsonRequestBehavior.AllowGet);
    
    0 讨论(0)
提交回复
热议问题