Skip to main content
 首页 » 编程设计

c#之Entity Framework DB首先发布加载相关实体(ASP.NET web api)

2024年01月31日27qq78292959

我一直在为这个相对简单的任务寻找答案,但没有成功。所以我想我会在这里问我的问题。我有一个简单的数据库,其中包含两个表,Books 和 Authors。

我的模型是由 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; } 
} 

这是自动生成的 Authors 模型:

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; } 
} 

这是 Controller 的一部分,用于获取 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 中保留对象引用,但这会破坏响应。这是唯一的选择吗?

请您参考如下方法:

如果你检查内部异常,它会说:

Self referencing loop detected for property 'Author' 

这告诉您,您的 Author 类引用回父类(即 Books,反之亦然)。

在您的网络 API 配置 (App_Start/WebApiConfig.cs) 中,添加:

public static class WebApiConfig 
{ 
    public static void Register(HttpConfiguration config) 
    { 
        // Prevent "Self referencing loop detected" error occurring for recursive objects 
        var serializerSettings = new JsonSerializerSettings() 
        { 
            ReferenceLoopHandling = ReferenceLoopHandling.Ignore 
        }; 
        config.Formatters.JsonFormatter.SerializerSettings = serializerSettings; 
    } 
} 

这告诉 JSON.NET 忽略引用回父对象的嵌套对象