Query: Support Include/ThenInclude for navigation on derived type
Is there a solution for using ThenInclude with polymorphic types?
Example model:
public abstract class BasePosition : Entity
{
public Order Order { get; set; }
}
public class GroupType : Entity
{}
public class GroupPosition : BasePosition
{
public GroupType GroupType { get; set; }
}
public class SalesPosition : BasePosition
{
public GroupPosition Group { get; set; }
}
public class Order : Entity
{
private List<BasePosition> positions;
public ICollection<BasePosition> Positions
=> positions ?? (positions = new List<BasePosition>());
}
Example query:
context.Set<Order>()
.Include(x => x.Positions)
.ThenInclude<SalesPosition>(x => x.Group) // Pseudo-Code, does obviously not work
.ThenInclude<GroupPosition>(x => x.GroupType) // Pseudo-Code, does obviously not work
AFAIK the only way this currently works is by manually querying the derived types after loading the base shape:
var o = context.Set<Order>()
.Where(o => o.Id == 1234)
.Single();
context.Set<GroupPosition>()
.Where(x => x.Order == o)
.Include(x => x.GroupType)
.Load();
context.Set<SalesPosition>()
.Where(x => x.Order == o)
.Include(x => x.Group)
.Load();
@davidroth As far as I know EF Core currently doesn't support any pattern you could use to express that you want query results to include navigations that only exist in derived types. Cc @anpete in case I am wrong.
As for how such pattern could look like, here is something we thought about in the past applied to the new ThenInclude method:
context.Set<Order>()
.Include(x => x.Positions)
.ThenInclude(x => (x as SalesPosition).Group)
.Include(x => x.Positions)
.ThenInclude(x => (x as GroupPosition).GroupType)
Of course, there are probably other things that could work and for instance the null-conditional operator would be better than this if it was supported in LINQ expressions.
@divega @davidroth I think this same issue applies to Include as well as ThenInclude right? If the type you are querying is a base type then there is no way to Include navigations defined on derived types in the hierarchy.
Yes, it would apply to both. Only this particular example had it in ThenInclude().
Does this also apply to base abstract classes?
public abstract class Entity
{
public DateTime CreatedAt { get; set; }
public DateTime UpdatedAt { get; set; }
public Guid? CreatedById { get; set; }
public Guid? UpdatedById { get; set; }
public User CreatedBy { get; set; }
public User UpdatedBy { get; set; }
}
public class Company : Entity
{
...
}
context.Set<Company>().Include(t => t.CreatedBy);
This results in: ArgumentNullException: Value cannot be null.
I'm writing an eager loading routine via graph building and expression trees and I'm running into this problem. Although the way I implemented it actually works as long as the actual database value is of the correct derived class
public static IQueryable<T> ThenIncludeQueryEx<T, TPreviousProperty, TProperty>(IQueryable<T> query, string propertyName)
where T : InternalObject
{
var pe = Expression.Parameter(typeof(TPreviousProperty));
var me = Expression.Convert(Expression.Property(pe, propertyName),typeof(TProperty));
var includeQuery = query as IIncludableQueryable<T, TPreviousProperty>;
query = includeQuery.ThenInclude(Expression.Lambda<Func<TPreviousProperty, TProperty>>(me, pe));
return query;
}
but it fails when the cast cannot be performed. Unfortunately, EF doesn't like Expression.TypeAs so I cannot combine it directly with Expression.Conditional to invoke a different path if the cast fails.
So considering this if the explicit type is saved to DB ( which is anyways saved as a Discriminator field ) the initial check could be included in the Where clause? Does that make sense? You would still need to run multiple queries based on each separate derived class possible to eagerly load all possible combinations
The Include/ThenInclude overloads that accept LINQ Expression trees like those @divega describe would help in some scenarios. What I need is reflection-friendly overloads that I call like this:
.Include( "Positions" )
.ThenInclude( typeof(SalesPosition), "Group" )
.Include( "Positions" )
.ThenInclude( typeof(GroupPosition), "GroupType" )
Currently, there's no ThenInclude that's tacked onto the reflection-friendly Include. But it would be useful here. Either that, or have Include search derived classes for chained properties specified in its string navigationPropertyPath parameter.
Why do I want this? I already defined a [Part] attribute that I use in OnModelCreating to enable cascade delete. Now I want to use this attribute to create an IncludeParts method.
I don't think the current workaround will work well for me since, after #1833 is implemented, I'll be filtering the upstream results before including the derived properties downstream.
@divega
context.Set<Order>() .Include(x => x.Positions) .ThenInclude(x => (x as SalesPosition).Group) .Include(x => x.Positions) .ThenInclude(x => (x as GroupPosition).GroupType)
This is feature is very compelling to me, although it may also be achieved in a shorter way, something like:
context.Set<Order>()
.Include(x => x.Positions)
.ThenInclude<SalesPosition>(sp => sp.Group)
.Include(x => x.Positions)
.ThenInclude<GroupPosition>(gp => gp.GroupType)
.ThenInclude(gt => gt.TypeName)
.Include<BusinessOrder>(bo => bo.Customer)
Having the ThenInclude's (and also the Include's - see last line, this is important) generic type argument used as an OfType filter, branching the local IIncludableQueryable to the desired type.
@divega @anpete @smitpatel this issue popped up in a conversation today
And also Include(property).Where(predicate).ThenInclude(property).Where(predicate)
@HappyNomad ditto. Constructing lambda expressions could be painful. There should be a reflection friendly version too, with and without a type filter (supporting inheritance).
@maumar - What are we planning to do here for now?
We are investigating supporting this via "as" and string based include for Preview2.
@anpete I'd just like to make sure you saw this, isn't it nicer than as?
We have discussed this in brief as a team. Though we haven't finalized exact sketch what it would be since we are bit short on time.
Here are some of the thoughts/experiments I did around the topic. (I am writing for Include though it is equally expanded for ThenInclude)
String based Include
IQueryable<Base>().Include("NavigationOnBase") //We interpret as navigation defined on base
IQueryable<Base>().Include(typeof(Derived), "NavigationOnDerived") // We interpret as navigation on the type arg.
This API looks clean. We have similar pattern for string based ModelBuilding support (HasForeignKey with one-to-one has such syntax). It will be an overload so there won't be confusion about inferring and I believe it would be visible enough. Also the first one can be re-written into second easily.
This is same as what @HappyNomad suggested though I did not understand what is "reflection friendly". As for PartAttribute we don't have plan to add it unless there is general purpose customer scenario.
Expression based Include
// Options 1
IQueryable<Base>().Include(e => e.NavigationOnBase)
IQueryable<Base>().Include(e => (e as Derived).NavigationOnDerived)
//Option 2
IQueryable<Base>().Include<Base, Base, ReferencedType>(e => e.NavigationOnBase)
IQueryable<Base>().Include<Base, Derived, DerivedReferencedType>(e => e.NavigationOnDerived)
We are looking to support option 1 here (Explained option 2 below why its bit cumbersome for user experience) The current version of Include already takes expression as parameter. The "as derived" part is just to give intellisense to user. We can start parsing such pattern of expression and generate include accordingly.
Option 2 There are 3 different Typed args to the function here. The incoming IQueryable type, the type used for expression lambda & the return type. Presently there are only 2 type args and they are inferred by compiler but if you want to add another type arg to change type of lambda then everything need to be typed explicitly. @weitzhandler - Your approach is kind of reaching there by giving typed arg to generic function but the other 2 also needs to be specified explicitly because compiler doesn't do "infer the rest" This makes option 1 a better choice, (less thing for user to figure out especially providing return type is very awkward).
I am still experimenting with different syntax for expression based include. Our goal is to provide good intellisense to user. We can always add extra overload if we find a good syntax and support the "as" syntax (which is somewhat similar to processing filtered include)
Given the time constraint we have, we are doing the "as" syntax and string based as above.
Include(property).Where(predicate).ThenInclude(property).Where(predicate)
In this syntax, all predicates will be applied to the first IQueryable only and not on the include. If you mean to apply the predicate on the included entity then its filtered include #1833
The issue for not supporting above syntax is
When user writes
context.Blogs.Include(b => b.Posts).Where(a => a.BlogId == 1).ToList()
It gives different meanings, if user wants to just Blog with Id 1 and all its post loaded
or All blogs but load only posts with BlogId=1.
Also for intellisense, what should be the type of "a" Blog or Post. It puts stricter requirement on user to specify include at certain place only (have to put last in most cases sort of). Hence its better not to involve such confusion.
@smitpatel
suggested though I did not understand what is "reflection friendly".
I believe he was referring to a convenient way of dynamically providing the includes, i.e. non LINQ-expressions. The one you mentioned earlier.
our approach is kind of reaching there by giving typed arg to generic function but the other 2 also needs to be specified explicitly because compiler doesn't do "infer the rest" This makes option 1 a better choice, (less thing for user to figure out especially providing return type is very awkward).
You're right. And BTW: Related.
If you mean to apply the predicate on the included entity then its filtered include #1833
Yep, that was it. Was just randomly pseudoing.
When user writes context.Blogs.Include(b => b.Posts).Where(a => a.BlogId == 1).ToList() It gives different meanings, if user wants to just Blog with Id 1 and all its post loaded or All blogs but load only posts with BlogId=1.
That's should be
context.Blogs.Include(b => b.Posts.Where(a => a.BlogId == 1)).ToList()
Notice the Where is inside the Include scope. Again, was pseudoing before but you understood me well anyway.
Thanks!
@smitpatel @anpete for option 2, did you try writing the lambda like this?
queryOfBase.Include((Derived e) => e.NavigationOnDerived);
@divega - It indeed passes compilation and also provides intellisense. I am investigating into chaining (ThenInclude) in generic complex. 🤞
Following compiles correctly providing good intellisense (For reference navigation cases, collection navigations & ThenInclude doesn't go well). It contains a good mix of current form of Includes (which applies to base only) as well as new form.
var includeOnDerivedTypes = new List<BasePosition>().AsQueryable()
.Include(bp => bp.Order) //Include On base
.Include((GroupPosition gp) => gp.GroupType) //Include on derived
.Include((SalesPosition sp) => sp.Group); //Include on derived
var thenIncludeOnDerivedTypes = new List<Order>().AsQueryable()
.Include(o => o.Positions)
.ThenInclude(p => p.Order) //ThenInclude on base
.Include(o => o.Positions)
.ThenInclude((GroupPosition gp) => gp.GroupType) //ThenInclude on derived
.Include(o => o.Positions)
.ThenInclude((SalesPosition sp) => sp.Group) //ThenInclude on derived
.ThenInclude(gp => gp.GroupType);
@smitpatel @divega @anpete @maumar I haven't read all of the discussion from last night. How confident are we that we are getting the API right? Are there open questions still?
@ajcvickers The latest proposal looks very nice. If other agree then I think we should go for it - Given the "loose" nature of LINQ expressions here, we are free to support alternative patterns in the future if we choose.
@anpete I'll let @divega make the call on the API. If he's okay, then let's try to get this in.