11

Я получаю сообщение об ошибке:содержит циклы и не может быть сериализован, если ссылка отключено отслеживание, json.net и WebAPI

Object graph for type 'System.Collections.Generic.List`1[[Proj.Model.Prom, Proj.Model, 
Version=1.0.0.0, Culture=neutral, PublicKeyToken=null]]' contains cycles and cannot be 
serialized if reference tracking is disabled. 

Чтения о том, что, кажется, сериализаторе, но Json.Net утверждает, быть решением, и я читал, что WebApi и Framework 4.5 имеют его по умолчанию. Так что это происходит по умолчанию? Если да, почему я все еще получаю эту ошибку?

Спасибо! Гильермо.

EDIT: Добавление кода

using System; 
using System.Collections.Generic; 
using System.Data.Spatial; 

namespace Proj.Model 
{ 
    public class Prom 
    { 
     public Prom() 
     { 
      this.Stores = new List<Store>(); 
      this.Branches = new List<Branch>(); 
      this.Products = new List<Product>(); 
     } 

     public int Id { get; set; } 
     public string Name { get; set; } 
     public DbGeography Location { get; set; } 
     public string Latitude { get; set; } 
     public string Longitude { get; set; } 
     public int StateId { get; set; } 
     public int CategoryId { get; set; } 

     public virtual ICollection<Store> Stores { get; set; } 
     public virtual ICollection<Branch> Branches { get; set; } 
     public virtual ICollection<Product> Products { get; set; } 

     public virtual Category Category { get; set; } 
     public virtual State State { get; set; } 

    } 
} 

using System; 
using System.Collections.Generic; 

namespace Proj.Model 
{ 
    public class Category 
    { 
     public Category() 
     { 
      this.Proms = new List<Prom>(); 
     } 

     public int Id { get; set; } 
     public string Name { get; set; } 
     public string Description { get; set; } 

     public virtual ICollection<Prom> Proms { get; set; } 
    } 
} 

Затем работает что-то вроде этого возвращает ошибку

public IEnumerable<Category> GetList(int estadoId, string idTiposTarjetasList) 
{ 
    var ids = "1,2,3,4".Split(','); 
    var intIds = ids.Select(int.Parse); 

    var Categories = Uow.Categorias.GetAllIncluding(c => c.Proms).ToList(); 
    foreach (var category in Categories) 
    { 
     var proms = category.Proms.Where(p => intIds.Contains(p.Id) && p.StateId == stateId).ToList(); 
     category.Proms = proms; 
    } 
    return Categories 
} 
+0

вы видите ту же проблему, когда вы отключите прокси? (http://msdn.microsoft.com/en-us/library/system.data.entity.infrastructure.dbcontextconfiguration.proxycreationenabled(v=VS.103).aspx) – Pawel

ответ

8

По умолчанию WebAPI установить 'PreserveReferencesHandling' на None.

Вы можете настроить Json.NET SerializerSettings в WebApiConfig.cs:

config.Formatters.JsonFormatter.SerializerSettings.PreserveReferencesHandling = 
    Newtonsoft.Json.PreserveReferencesHandling.All; 
+1

Добавил, что, но я все равно получаю ту же ошибку – polonskyg

+0

Можете ли вы поделиться своим классом Proj.Model.Prom? –

+0

Добавил код к исходному вопросу. – polonskyg

3

Следующая помогли мне:

config.Formatters.JsonFormatter.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore; 
config.Formatters.JsonFormatter.SerializerSettings.PreserveReferencesHandling = Newtonsoft.Json.PreserveReferencesHandling.None;