实体框架WebApi循环依赖性序列化错误

时间:2012-12-06 21:24:11

标签: asp.net json entity-framework asp.net-web-api circular-dependency

我想,我已经阅读了有关此错误的所有内容,并尝试了所有内容。这是我的模特:

主:

public class Trip
{
    public int TripId { get; set; }
    public string Name { get; set; }
    public string ShortDescription { get; set; }
    public string Country { get; set; }
    public float BasicPrice { get; set; }
    public virtual ICollection<ApartmentType> ApartmentType { get; set; }
    public virtual ICollection<TransportMethod> TransportMethod { get; set; }
    public virtual ICollection<FeedingType> FeedingType { get; set; }
}

ApartmentType:

public class TransportMethod
{
    public int TransportMethodId { get; set; }
    public int TripId { get; set; }
    public string Name { get; set; }
    public float Price { get; set; }
}

FeedingType:

public class FeedingType
{
    public int FeedingTypeId { get; set; }
    public int TripId { get; set; }
    public string Description { get; set; }
    public float Price { get; set; }
}

TransportType:

public class TransportMethod
{
    public int TransportMethodId { get; set; }
    public int TripId { get; set; }
    public string Name { get; set; }
    public float Price { get; set; }
}

当序列化Trip实体时,我得到循环依赖性错误。我试过的事情:

  1. 在DbContext中禁用延迟加载。
  2. 添加      json.SerializerSettings.PreserveReferencesHandling = Newtonsoft.Json.PreserveReferencesHandling.All;到GLobal.asax

  3. 在每个子实体的TripId中添加装饰器[IgnoreDataMember]。

  4. 将此实体映射到不包含ICollection成员的ViewModel。 - 这项工作正常,但在某些时候我会希望将这些列表提供给客户。
  5. 我真的不知道发生了什么事。我错过了什么?我真的无法发现任何循环依赖。

1 个答案:

答案 0 :(得分:1)

您是否尝试将[JsonIgnore]属性添加到子实体的TripId

http://james.newtonking.com/projects/json/help/html/T_Newtonsoft_Json_JsonIgnoreAttribute.htm

或设置

json.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;

相关问题