Reputation: 321
I insert an Entity with this request and it is successful.
Request
{
"Title": "Book 1"
}
Response
{
"id": 1,
"title": "Book 1",
"serialId": "00000000-0000-0000-0000-000000000000",
"borrows": null,
"votes": null
}
I checked the database and there is a Book row with id = 1. But now when I try to fetch a list it returns an error because the DbSet is empty after the insert.
var books = db.Books; // count = 0
The response for /books
is the exception:
"exceptionMessage": "The 'ObjectContent`1' type failed to serialize the response body for content type 'application/json; charset=utf-8'.",
And the inner exception includes Error getting value from 'Borrows'
so I thought it might be to do with how the relationship is defined, also there are no Borrow entities in the database yet.
"exceptionMessage": "Error getting value from 'Borrows' on 'System.Data.Entity.DynamicProxies.Book_6E27A1F717202EA02AE923CCC6405EF9A501FE9A54A71841CEB43E942224D88A'.",
"exceptionType": "Newtonsoft.Json.JsonSerializationException",
The Book
entity has a navigation property of List on it with a defined relationship:
modelBuilder.Entity<Book>().HasMany<Borrow>(b => b.Borrows);
Book's entity defined with a list of Borrow entities:
public virtual List<Borrow> Borrows { get; set; }
The migration of Book only has it's Id for the primary key:
CreateTable(
"dbo.Books",
c => new
{
Id = c.Int(nullable: false, identity: true),
Title = c.String(),
SerialId = c.Guid(nullable: false),
})
.PrimaryKey(t => t.Id);
Question: What is causing this exception, is it something to do with how I defined the relationship between Book
and Borrow
? I've seen examples of relationships having to be defined in both directions, do I need to define the relationship to not require a borrow somehow? I've noticed DbSet Count = 0 occur in the past when there have been results so I think it could also be an issue with NewtonSoft. I'm not sure what is going on here.
Full exception: https://pastebin.com/raw/BvUfBnKU
Upvotes: 2
Views: 4120
Reputation: 321
I got it working by using this answer: https://stackoverflow.com/a/14317598/11419029, returning a List rather than IQueryably.
I changed it to this:
// GET: api/Books
public List<Book> GetBooks()
{
var books = db.Books.ToList();
return books;
}
From this:
// GET: api/Books
public IQueryable<Book> GetBooks()
{
var books = db.Books;
return books;
}
But I'm still not sure what the problem was, another answer said it was to do with a query being executed while iterating results of another query. Triggering lazy loading. Now I'm concerned it is executing nested queries, querying borrows for every instance of a book.
Upvotes: 2