Consider a database with Order
and OrderLines
tables and one-to-many relationship between them (this is for MCVE; the actual context is more complex). If I scaffold the model, I get the following:
public partial class Order {
public virtual ICollection<OrderLines> OrderLines {get; set;}
}
and
public partial class OrderLines {
public virtual int OrderId {get; set;}
public virtual Order Order {get; set;}
}
Now, if I generate OrdersController, the GET method is also quite straightforward:
[HttpGet]
public ActionResult<IEnumerable<Order>> Order() {
return _context.Order.ToList();
}
And I get a nice JSON string in return. However, if I add Include() to the get method like this:
return _context.Order.Include(o => o.OrderLines).ToList();
the resulting string is cut in the middle. When I debug, it seems that the program gets into infinite loop from OrderLines to Order and then back to OrderLines. If I remove Order
variable from OrderLines
and only leave OrderId
, everything works fine (which supports my hypothesis about infinite loop).
Obviously, it is somewhat primitive example; I should be using ViewModel - but still, shouldn't the code above be valid? I haven't used Include() for years, but I am pretty sure that in earlier versions of EF it was working fine.
What is the recommended way to get the object and its child collection?