brroshan brroshan - 5 months ago 31
ASP.NET (C#) Question

Entity Framework DB first issues loading related entities (ASP.NET web api)

I've been looking for answers for this relatively simple task but with no success. So I thought I'd ask my question here. I have got a simple database with two tables, Books and Authors.

enter image description here

I got my models generated by the ADO.NET entity data model. This is the auto-generated Books model:

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

And this is the auto-generated Authors model:

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

And this is a part of the controller, the method for getting a list of all the books in JSON format.

// api/books
public IQueryable<Book> GetBooks()
// return db.Books.Include(x => x.Authors); Don't work
return db.Books;

This is my JS for calling the endpoint:

.done(function (data) {
.fail(function (xhr) { console.log(xhr.responseText) });

Nothing fancy, just trying to make a GET request and receiving a list of all the books and their related authors.

This is a portion of the error message:

{"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":"

I have tried preserving object references in JSON but that mangles the response. Is that is the only option?

Answer Source

If you examine the inner exception it says:

Self referencing loop detected for property 'Author'

This tells you that your Author class references back to the parent (i.e. Books or vice versa).

In your web api config (App_Start/WebApiConfig.cs), add this:

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;

This tells JSON.NET to ignore nested objects referring back to the parent object

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download