The Expression is not valid in an include function

Asjad Butt 71 Reputation points
2022-10-25T08:26:55.243+00:00

Hi im trying to get some data from the foreign key column and when i use the then include operation i get the following error

System.InvalidOperationException: The expression 'p.BranchName' 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.

ill attach the repository code and the entities
253799-image.png
253836-image.png
253747-image.png
and the post man error
253784-image.png

ASP.NET Core
ASP.NET Core
A set of technologies in the .NET Framework for building web applications and XML web services.
4,208 questions
0 comments No comments
{count} votes

1 answer

Sort by: Most helpful
  1. Zhi Lv - MSFT 32,021 Reputation points Microsoft Vendor
    2022-10-25T09:35:07.43+00:00

    Hi @Asjad Butt ,

    System.InvalidOperationException: The expression 'p.BranchName' 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.

    When using the Include or ThenInclude , we need to specify a navigation property, but in your query statement, the BranchName is just a string type, instead of the navigation property. So, it will show the above error.

    To solve it, try to modify your code as below: I assume you want to load the BranchAdmin entity, change the BranchName to BranchAdmin:

            var students = await context.Students  
                .Include(p => p.Branch)  
                .ThenInclude(b => b.BranchAdmin)  
                .Include(p => p.Guardian)  
                .ToListAsync();  
    

    If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".
    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    Best regards,
    Dillion