Consider the following model:
public abstract class A
{
public enum T { B, C, D }
public int Id { get; set; }
public int? ParentId { get; set; }
public A? Parent { get; set; }
public virtual ICollection<A> Children { get; set; } = []; // an B has Cs and a C has Ds as children
public virtual ICollection<E> Es { get; set; } = [];
}
public class B
: A
{
}
public class C
: A
{
}
public class D
: A
{
public virtual ICollection<F> Fs { get; set; } = [];
}
public class E
{
}
public class F
{
}
My question is: How do I include everything in a single query of A using eager loading and fluent syntax, so basically I want to do something like the follwing (which fails by throwing an exception in the last ThenInclude):
private IQueriable<A> As => _dbContext.As
.Include(b => b.Children)
.Include(b => b.Es)
.ThenInclude(c => c.Children)
// how to include c.Es ?
.ThenInclude(d => (d as D).Fs)
// and how to I include d.Es ?
I’ve tried casting C.Children using linq’s Cast() or filtering with OfType() but the exception message (which is thrown then) tells me there are only Where, OrderBy and ThenBy available and casting should be done using ‘as’ operator or explicit casting, non of them work in the shown example.