2013-03-29 24 views
3

我的桌面wpf應用程序與mvc 4 web api進行通信。我正在嘗試讀取所有數據庫條目。這是簡單的接口:考慮使用DataContractResolver序列化錯誤

public interface IEventRepository 
{ 
    IEnumerable<Event> GetAll(); 
} 

這是庫:

public class EventRepository : IEventRepository 
{ 
    private List<Event> events = new List<Event>(); 
    public EventRepository() 
    { 
     HeronEntities context = new HeronEntities(); 
     events = context.Events.ToList(); 
    } 

    public IEnumerable<Event> GetAll() 
    { 
     return events; 
    } 
} 

這是控制器:

public class EventController : ApiController 
{ 
    static readonly IEventRepository repository = new EventRepository(); 

    public IEnumerable<Event> GetAllEvents() 
    { 
     return repository.GetAll(); 
    } 
} 

事件類看起來是這樣的:

public partial class Event 
{ 
    public Event() 
    { 
     this.Comments = new HashSet<Comment>(); 
     this.Rates = new HashSet<Rate>(); 
     this.RawDates = new HashSet<RawDate>(); 
    } 

    public int ID { get; set; } 
    public string Title { get; set; } 
    public string Summary { get; set; } 
    public string SiteURL { get; set; } 
    public string ContactEmail { get; set; } 
    public string LogoURL { get; set; } 
    public int EventType_ID { get; set; } 
    public Nullable<int> Location_ID { get; set; } 
    public Nullable<System.DateTime> BegginingDate { get; set; } 
    public string nTrain { get; set; } 
    public string Content { get; set; } 

    public virtual ICollection<Comment> Comments { get; set; } 
    public virtual Conference Conference { get; set; } 
    public virtual ICollection<Rate> Rates { get; set; } 
    public virtual ICollection<RawDate> RawDates { get; set; } 
    public virtual EventType EventType { get; set; } 
    public virtual Location Location { get; set; } 
} 

當我嘗試訪問控制器時,我得到上面提到的錯誤failed to serialize the response body for content type。類的序列化存在一些問題Event。我使用與包含基本類型的類完全相同的代碼,並且它完美地工作。什麼是克服這種序列化問題的最好方法?

回答

4

我禁用了延遲加載和代理類生成。這解決了問題。

public EventRepository() 
    { 
     HeronEntities context = new HeronEntities(); 
     context.Configuration.LazyLoadingEnabled = false; 
     context.Configuration.ProxyCreationEnabled = false; 
     events = context.Events.ToList(); 
    } 
相關問題