在MVC中检测到属性Error的自引用循环
本文关键字:Error 自引用 循环 属性 MVC 检测 | 更新日期: 2023-09-27 18:19:37
我在淘汰中使用MVVM。当我尝试在mvc中对对象进行Searalize时,我得到了以下错误。有谁能帮我做这件事吗。
错误行:返回Json(JsonConvert.SerializeObject(resultwrapper),JsonRequestBehavior.AllowGet)
错误为类型为"DCL.HotelDetails"的属性"HotelDetails"检测到自引用循环。路径为"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);
如果HotelImages
有对HotelDetails
的引用,那么您可能会得到一个循环引用。您可以通过设置PreserveReferencesHandling = PreserveReferencesHandling.Objects
来防止这种情况发生。例如
string json = JsonConvert.SerializeObject(resultwrapper, Formatting.Indented, new JsonSerializerSettings { PreserveReferencesHandling = PreserveReferencesHandling.Objects });
参考文件