2013-03-29 56 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(); 
    }