检测到MVC中属性Error的自引用循环

时间:2014-08-27 07:44:24

标签: c# asp.net-mvc json linq

我在淘汰赛中使用MVVM。当我尝试在mvc中对对象进行Searialize时,我得到以下错误。任何人都可以帮助我。

错误行:返回Json(JsonConvert.SerializeObject(resultwrapper),JsonRequestBehavior.AllowGet);

错误 检测到属性的自我引用循环' HotelDetails'与类型' DCL.HotelDetails'。 Path' HotelDetails [3] .HotelImages [0]'。

我的模特

 public class HotelDetails : Entity
    {

        public HotelDetails()
    {
        this.HotelImages = new List<HotelImages>();
    } 
        [Key]
        public virtual Guid Id { get; set; }

        public virtual Guid HotelChainId { get; set; }

        public virtual int OldHotel { get; set; }

        public virtual string StarRating { get; set; }

        public virtual string PostalCode { get; set; }

        public virtual string Longtitude { get; set; }

        public virtual string Latitude { get; set; }

        public virtual string DestinationID { get; set; }

        public virtual string HotelLocation { get; set; }

        public virtual string PhoneNumber { get; set; }

        public virtual string Address { get; set; }

        public virtual string HotelArea { get; set; }

        public virtual string HotelType { get; set; }

        public virtual string HotelTheme { get; set; }


        //public virtual Destination Destination { get; set; }

        public virtual List<HotelImages> HotelImages { get; set; }

    }

我的C#代码

 IEnumerable<IGrouping<string, DCL.JsonMatrixModel.availableHotels>> quer =
      from ff in ddd
      from ss in ff.availableHotels
      group ss by ss.hotelCode;


            List<HotelDetails> lsthoteldetails = new List<HotelDetails>();
            List<HotelImages> lsthotelimages = new List<HotelImages>();


            HotelDetails _hoteldetails;


            foreach (var y in quer)
            {
                _hoteldetails = new HotelDetails();


                string ss = y.Key;
                _hoteldetails = db.HotelDetails.Where(x => x.Code == ss).FirstOrDefault();
                if (_hoteldetails != null)
                {
                    lsthotelimages = db.HotelImages.Where(x => x.HotelDetailsId == _hoteldetails.Id).ToList();
                    _hoteldetails.HotelImages = lsthotelimages;
                    lsthoteldetails.Add(_hoteldetails);
                }





            }
           // resultwrapper.key = "kdkdk";
            resultwrapper.LoadData();

            resultwrapper.HotelDetails = lsthoteldetails;



            return Json(JsonConvert.SerializeObject(resultwrapper), JsonRequestBehavior.AllowGet);

1 个答案:

答案 0 :(得分:0)

如果HotelImages引用了HotelDetails,那么您很可能会获得循环引用。您可以使用PreserveReferencesHandling = PreserveReferencesHandling.Objects设置来阻止此操作。例如

string json = JsonConvert.SerializeObject(resultwrapper, Formatting.Indented, new JsonSerializerSettings { PreserveReferencesHandling = PreserveReferencesHandling.Objects });

Refer documentation