2013-12-11 1 views
0

처음으로 내 아키텍처에 대해 알려 드리고 싶습니다. ApiController 기능Asp.Net Mvc Web Api Json 형식화 자 문제

: 이야기 테이블에 대한 나의 이야기 클래스는

public class Tale 
{ 
    [ScaffoldColumnAttribute(false)] 
    public int TaleId { get; set; } 
    public string TaleName { get; set; } 
    public string Content { get; set; } 
    public string VoicePath { get; set; } 
    public virtual ICollection<Category> Category { get; set; } 
} 

그 ı 같이 분류 표

public class Category 
{ 
    public int CategoryId { get; set; } 
    public string CategoryName { get; set; } 
    public virtual ICollection<Tale> Tales { get; set; } 
} 

에 대한 나의 카테고리 클래스 내 TalesCategory 테이블

modelBuilder.Entity<Tale>() 
      .HasMany<Category>(u => u.Category) 
      .WithMany(r => r.Tales) 
      .Map(c => c.ToTable("TalesCategory") 
         .MapLeftKey("TaleKey") 
         .MapRightKey("CategoryKey")); 

그리고 그것의 내 TaleController를 만들

public IEnumerable<Tale> GetAllTales() 
    { 
     return TaleService.FindAllTale(); 
    } 
내 WebApiConfig

config.Formatters.Clear(); 
     config.Formatters.Add(new JsonMediaTypeFormatter()); 

나는 "/ API/이야기"나는 내 이야기의 목록 싶지만이 오류을 작성하는 경우. 나는 JsonMediaFormatter를 써야한다고 생각하고 약간의 코드를 시도했지만 성공하지 못했습니다. 내가 무엇을 할 수 있을지? .NET Framework 4.5를 사용합니다.

{"Message":"An error has occurred.","ExceptionMessage":"The 'ObjectContent`1' type failed to serialize the response body for content type 'application/json; charset=utf-8'.","ExceptionType":"System.InvalidOperationException","StackTrace":null,"InnerException":{"Message":"An error has occurred.","ExceptionMessage":"Self referencing loop detected with type 'System.Data.Entity.DynamicProxies.Tale_B48C4EAA8B3983ECA938C57C1764611B3C06FAC3348891DAC636EBEBF05EA8E2'. Path '[0].Category[0].Tales'.","ExceptionType":"Newtonsoft.Json.JsonSerializationException","StackTrace":" konum: Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.CheckForCircularReference(JsonWriter writer, Object value, JsonProperty property, JsonContract contract, JsonContainerContract containerContract, JsonProperty containerProperty)\r\n konum: Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.SerializeList(JsonWriter writer, IWrappedCollection values, JsonArrayContract contract, JsonProperty member, JsonContainerContract collectionContract, JsonProperty containerProperty)\r\n konum: 
+1

의 중복 가능성 http://stackoverflow.com/questions/7397207/json-net-error-self-referencing-loop -detected-for-type) – CodeCaster

답변

0

EF 클래스의 탐색 속성으로 인해 픽업되는 순환 참조를 해제해야합니다.

시도

public IEnumerable<Tale> GetAllTales() 
{ 
    return TaleService.FindAllTale().Select(x=> new Tale 
        { 
         TaleId = x.TaleId, 
         TaleName = x.TaleName, 
         ... 
        }); 
} 
[형 검출 JSON.NET 오류 자기 - 참조 루프 (
+0

알 겠어.하지만이 결과에서 카테고리 ID를보고 싶다. 내가 ur 예제 {TaleId = x.TaleId, ... Category = x.Category}로 코드를 편집하고 ı이 오류를 가져옵니다. "System.Data.EntityCommandExecutionException '유형의 예외가 System.Data.Entity.dll에서 발생했지만 사용자 코드에서 처리되지 않았습니다. " ICollection 에 문제가 있습니다. 내 첫 번째 코드를 사용하기 때문에 내 머리가 약간 혼란 스럽다. – BerdaN

+0

카테고리에도 "선택"을 사용하십시오. 마찬가지로 :'Category = x.Category.Select (y => 새로운 카테고리 {CategoryId = y.CategoryId, ...})' –

+0

답변 주셔서 감사합니다. 그러나 지금은 ı 변환 유형 오류를 취합니다. 내가 말했듯이 Category는 ICollection <> " 'System.Collections.Generic.Intnumerable '형식을 'System.Collections.Generic.ICollection '형식으로 암시 적으로 변환 할 수 없습니다. 명시 적 변환 " – BerdaN

관련 문제