【发布时间】:2015-06-01 17:28:05
【问题描述】:
我一直在寻找这个相对简单的任务的答案,但没有成功。所以我想我会在这里问我的问题。我有一个简单的数据库,其中包含两个表,书籍和作者。
我的模型由 ADO.NET 实体数据模型生成。这是自动生成的 Books 模型:
public partial class Book
{
public int BookID { get; set; }
public string Title { get; set; }
public string Description { get; set; }
public int ISBN { get; set; }
public int AuthorID { get; set; }
public virtual Author Author { get; set; }
}
这是自动生成的作者模型:
public partial class Author
{
public Author()
{
this.Books = new HashSet<Book>();
}
public int AuthorID { get; set; }
public string Name { get; set; }
public virtual ICollection<Book> Books { get; set; }
}
这是控制器的一部分,用于获取 JSON 格式的所有书籍列表的方法。
// api/books
public IQueryable<Book> GetBooks()
{
// return db.Books.Include(x => x.Authors); Don't work
return db.Books;
}
这是我调用端点的 JS:
$.getJSON("api/books")
.done(function (data) {
console.log(data);
})
.fail(function (xhr) { console.log(xhr.responseText) });
没什么特别的,只是尝试发出 GET 请求并接收所有书籍及其相关作者的列表。
这是错误信息的一部分:
{"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 for property 'Author' with type 'System.Data.Entity.DynamicProxies.Author_5968F94A1BBB745A30D62CD59D0AC5F96A198B3F16F0EA2C2F61575F70034886'. Path '[0].Books[0]'.","ExceptionType":"Newtonsoft.Json.JsonSerializationException","StackTrace":"
我尝试在 JSON 中保留对象引用,但这会破坏响应。这是唯一的选择吗?
【问题讨论】:
标签: c# asp.net json entity-framework