EDIT: This is the answer Is recursive query possible in LINQ It was already answered there must have missed that one.
I'm on .NET Core 2.2.
I've looked through multiple questions asked on this site and none of the answers worked for me.
My Model looks like this (simplified):
public class Product
{
/// <summary>
/// Gets or sets the Id.
/// </summary>
public string Id { get; set; }
/// <summary>
/// Gets or sets the code.
/// </summary>
public string Code { get; set; }
/// <summary>
/// Gets or sets the properties.
/// </summary>
public List<Property> Properties { get; set; }
/// <summary>
/// Gets or sets the products
/// </summary>
public List<Product> Products { get; set; }
}
public class Property
{
/// <summary>
/// Gets or sets the Id.
/// </summary>
public string Id { get; set; }
/// <summary>
/// Gets or sets the code
/// </summary>
public string Code { get; set; }
}
I am trying to load a product with all it's sub products also including the properties of all the products.
First, I've been able to load all products recursively but I honestly don't know why it works.
I've tried this:
var products1 = this._context.Products.Where(x => x.Code == "TEST").Include(x => x.Products);
And it would only load the products of the first level products.
Then by pure luck/mistake I've left this line before the aforementioned one:
this._context.Products.ToList()
Then, the first line actually loaded all products recursively... nice I guess?
Anyway, now what I'm trying to do is load all products recursively while also loading all of their properties.
I've tried a couple of things including the shady-looking:
this._context.Products.Where(x => x.Code == "TEST").Include(x => x.Properties)
.Include(x => x.Products).ThenInclude(x => x.Properties);
But whatever I do I will only load the properties of the products of the first level of recursion. I still fully load all products recursively but only the first 2 levels have their properties loaded.
So ultimately my question is how do I do that? As a bonus question that might be answered anyway if the real question is answered: why do I need to put this line:
this._context.Products.ToList()
before this line:
var products1 = this._context.Products.Where(x => x.Code == "TEST").Include(x => x.Products);
To load the products recursively?
EDIT: Note that I know I can recursively load all Product/Property with multiple queries (one for each Product) in a loop but I definitely want to avoid that if possible.