I really am done with this, but at least I want to know what's going on. Here we go:
My project is an ASP.NET Core Web Application with Code First Entity Framework Core and an Angular frontend.
I want to control when to load referenced objects. They can be useful, but they can also create circular references with internal errors on the frontend. (JSON would be infinitely long.)
Models:
class Book {
public virtual ICollection<Page> Pages { get; set; }
...simple properties
}
class Page {
public virtual Book Book { get; set; }
...simple properties
}
In this example, every book from books will have an empty/null Pages list.
using (var context = new MoneyStatsContext())
{
var books = context.Books.Where(rule => rule.State == 1).ToList();
}
In this example, the Pages lists are not null, and every Page will have it's Book property set. Thus creating a circular reference.
using (var context = new MoneyStatsContext())
{
var books = context.Books.Where(rule => rule.State == 1).Include(x => x.Pages).ToList();
}
How do I avoid the circular reference? Do I really have no other (simpler) choice than creating a new model and manually specifying each property?
.Select(new Book() {
...setting each property by hand
}
Not-working-solutions I've found:
- Tried setting this false and true. Doesn't seem to change anything.
public MyContext()
{
this.ChangeTracker.LazyLoadingEnabled = false;
}
- Tried specifying this in Startup.cs, but options doesn't have a SerializerSettings property.
services.AddMvc().AddJsonOptions(options =>
{
options.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;
});
Any help would be appreciated. Thanks in advance.