错误:序列化Entity Framework类

public IList SearchEvents(DateTime fromDate, DateTime toDate, int categoryId, string eventName ) { var query = context.Events.Include("City").Where(e => e.EventCategoryID == (categoryId = fromDate.Month) && (e.EndDate.Value.Month = fromDate.Day) && (e.EndDate.Value.Day = fromDate.Year) && (e.EndDate.Value.Year <= toDate.Year) && string.IsNullOrEmpty(eventName)? eventName.Contains(e.EventName): eventName.Contains(eventName)); return query.ToList(); } public JsonResult SearchEvents(string from,string to,int categoryId, string eventName) { DateTime frmDate= Convert.ToDateTime(from); DateTime toDate = Convert.ToDateTime(to); var list = _eventRepository.SearchEvents(frmDate,toDate,categoryId,eventName); return Json(list, JsonRequestBehavior.AllowGet); } 

我得到错误像:

 Error :' A circular reference was detected while serializing an object of type 'CGWeb.Models.Repositories.Models.Event'. 

如何在不删除虚拟关键字的情况下解决此问题?。请分享..!

//

@Marc Gravell这是我的模特

  [Table("Table_Events")] public partial class Event { [Key] public int ID { get; set; } //public int? LocationId { get; set; } //public int? ImageId { get; set; } public string EventName { get; set; } [NotMapped] public string EventAddress { get; set; } public string EventUrl { get; set; } public string EventDesc { get; set; } public Nullable StartDate { get; set; } public Nullable EndDate { get; set; } public Nullable EventCategoryID { get; set; } public int CityID { get; set; } public int Viewed { get; set; } [ForeignKey("EventCategoryID")] public virtual EventCategory EventCategory { get; set; } //[ForeignKey("ImageId")] [NotMapped] public virtual ImageViewModel Image { get; set; } //[ForeignKey("LocationId")] //public virtual Location Location { get; set; } [ForeignKey("CityID")] public virtual City City { get; set; } [NotMapped] public bool ISSponsorship { get; set; } [NotMapped] public Organizer Organizer { get; set; } //[NotMapped] [ForeignKey("EventId")] public virtual IList Attending { get; set; } } 

这与virtual关键字无关; 它与对象图有关。 我们无法看到您的图形,但这里的经典场景是父/子双向关系,即父级具有.Parent且子级具有.Parent

树序列化器(例如xml,json等)通常会遍历任何未明确标记为忽略的成员。 因此,当它永远绕过那个圆圈时,你会得到一个无限循环。 选项:

  • 在这个边界使用非循环DTO(这就是我要做的)
  • 标记违规的反向引用以进行排除(每个序列化程序的机制因此而异)