Skip to content

Query: Support Include/ThenInclude for navigation on derived type #3910

Closed

Description

@davidroth

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();

Activity

  1. changed the title [-]"ThenInclude" with polymorphic collections[/-] [+]"ThenInclude" with polymorphic types in a collection[/+] on Nov 27, 2015
  2. divega commented on Nov 27, 2015

    @divega
    Contributor

    @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.

  3. added this to the Backlog milestone on Dec 1, 2015
  4. rowanmiller commented on Dec 23, 2015

    @rowanmiller
    Contributor

    @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.

  5. divega commented on Dec 24, 2015

    @divega
    Contributor

    Yes, it would apply to both. Only this particular example had it in ThenInclude().

  6. changed the title [-]"ThenInclude" with polymorphic types in a collection[/-] [+]Query: Support Include/ThenInclude for navigation on derived type[/+] on Dec 28, 2015
  7. gregbty commented on Jan 7, 2016

    @gregbty

    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.

  8. zedr0n commented on May 28, 2016

    @zedr0n

    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

  9. HappyNomad commented on Jan 10, 2017

    @HappyNomad

    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.

  10. weitzhandler commented on May 22, 2017

    @weitzhandler
    Contributor

    @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.

  11. maumar commented on Jun 8, 2017

    @maumar
    Contributor

    @divega @anpete @smitpatel this issue popped up in a conversation today

  12. self-assigned this
    on Jun 8, 2017
  13. modified the milestones: 2.0.0, Backlog on Jun 8, 2017
  14. 61 remaining items

  15. HappyNomad commented on Feb 13, 2018

    @HappyNomad

    After this is released in 2.1, will it be safe (i.e. no exceptions thrown) to call the string based include on a collection with items of mixed derived types, such some have the included property and others don't? To be useful, it seems the answer must be 'yes'. I'm just double checking.

  16. anpete commented on Feb 13, 2018

    @anpete
    Contributor
  17. HappyNomad commented on Feb 13, 2018

    @HappyNomad

    @anpete Thanks, good to know. Looks like you decided against a string based include overload that takes a System.Type as suggested here and echoed here.

  18. anpete commented on Feb 13, 2018

    @anpete
    Contributor

    @HappyNomad Feel free to create a separate issue for this, or send a PR. 😉

  19. HappyNomad commented on Feb 13, 2018

    @HappyNomad

    @anpete No, that's okay. I was just clarifying. In that same comment, I also suggested the alternative that you did end up implementing.

    Either that, or have Include search derived classes for chained properties specified in its string navigationPropertyPath parameter.

    I assume that's how it works in 2.1.

  20. maumar commented on Feb 14, 2018

    @maumar
    Contributor

    @iudelsmann looks like you are hitting #10101 - try performing Include as the last operation:

    _context.Services.OrderBy(service => ((Course)service).Type.Name).Skip((pageNumber- 1) * pageSize).Take(pageSize).Include(service => service.Category).ToListAsync();
    
  21. iudelsmann commented on Feb 15, 2018

    @iudelsmann

    @maumar That did not work, it is still performing a inner join. Observe that I'm not Includeing the CourseType from the Course entity, as in 2.0 we can't include derived navigation properties. So I think it might work in 2.1 if I include it, as it should perform the appropriate left join, would you agree?

  22. maumar commented on Feb 16, 2018

    @maumar
    Contributor

    @iudelsmann ahh, I understand now. In fact INNER JOIN for this scenario is the current behavior even in the current developer bits. Problem here is that navigation "Service.Type" is required and this is how we determine whether INNER JOIN or LEFT JOIN should be produced. (we don't take into account that the navigation is declared on derived). I have filed #10988 to track this issue.

  23. SvenEV commented on Feb 28, 2018

    @SvenEV

    After this is released in 2.1, will it be safe (i.e. no exceptions thrown) to call the string based include on a collection with items of mixed derived types, such some have the included property and others don't? To be useful, it seems the answer must be 'yes'. I'm just double checking.

    Yes!

    @anpete Should this be supported already in the current preview (2.1 preview 1)?

  24. modified the milestones: , 2.1.0 on Nov 11, 2019
  25. ArminShoeibi commented on Jan 27, 2023

    @ArminShoeibi

    Hello there folks,

    I have a simple Hierarchy that uses TPC

    public class Order : EntityBase
    {
        public long OrderId { get; set; }
        public IList<OrderLineItem> OrderLineItems { get; set; }
    }
    
    public abstract class OrderLineItem : EntityBase
    {
        public long OrderLineItemId { get; set; }
        public Order Order { get; set; }
        public long OrderId { get; set; }
    }
    
    public class OrderLineItemDomesticFlight : OrderLineItem
    {
        public DateTimeOffset DepartureDateTime { get; set; }
        public DateTimeOffset ArrivalDateTime { get; set; }
        public string Origin { get; set; }
        public string Destination { get; set; }
        public string Airline { get; set; }
    }
    
    public class OrderLineItemTrain : OrderLineItem
    {
        public string Origin { get; set; }
        public string Destination { get; set; }
    }

    But I don't know how to get all types of OrderLineItems when fetching an Order from the database.

    I have read this doc https://learn.microsoft.com/en-us/ef/core/querying/related-data/eager#include-on-derived-types but I didn't figure it out.

    for example, this code does not work:

            var order = await _db.Orders
                                 .Include(o => o.OrderLineItems as OrderLineItemDomesticFlight)
                                 .Include(o => o.OrderLineItems as OrderLineItemTrain)
                                 .FirstOrDefaultAsync(o => o.OrderId == 1);

    and this is the exception:

    System.InvalidOperationException: The expression '(o.OrderLineItems As OrderLineItemDomesticFlight)' is invalid inside an 'Include' operation, since it does not represent a property access: 't => t.MyProperty'. To target navigations declared on derived types, use casting ('t => ((Derived)t).MyProperty') or the 'as' operator ('t => (t as Derived).MyProperty'). Collection navigation access can be filtered by composing Where, OrderBy(Descending), ThenBy(Descending), Skip or Take operations.

  26. ArminShoeibi commented on Jan 27, 2023

    @ArminShoeibi

    I found the answer.
    We don't need many Includes, you just need to set polymorphic JSON serialization or if you want the real data you can use OfType Method.

            var order = await _db.Orders
                                 .Include(o => o.OrderLineItems)
                                 .FirstOrDefaultAsync(o => o.OrderId == orderId);
    
            var train = order.OrderLineItems.OfType<OrderLineItemTrain>().ToList();
            var domFlight = order.OrderLineItems.OfType<OrderLineItemDomesticFlight>().ToList();
  27. added theissue type on Jun 15, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

No labels
No labels

Projects

No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions