© 2026 Hedgehog Software, LLC

TwitterGitHubDiscord
More
CommunitiesDocsAboutTermsPrivacy
Search
Star
Setup for Free
C#C
C#•3y ago•
10 replies
linqisnice

Polymorphic query handling in EF Core - Thoughts?

So I'm having to deal a lot with entity polymorphism and querying the db to avoid having to execute multiple separate queries. I'm not sure about best practices here, but i also have to eagerload certain nav props from the derived types. Anyone know a better way than this?

        private async Task<IReadOnlyList<CoreProduct>> GetCoreProducts(IEnumerable<IProductRequest> requests, int internalPropertyId)
        {
            var query = _dbContext.Products.OfType<CoreProduct>().AsSplitQuery();

            foreach(var request in requests.GroupBy(x => x.GetType(), x => x))
            {
                query = request switch
                {
                    IAccommodationRequest => AccommodationQuery(query),
                    // more types here
                    _ => throw new UnreachableException()
                };
            }

            return await query.Where(x => x.InternalPropertyId == internalPropertyId && requests.Select(x => x.ProductId).Contains(x.Id)).ToListAsync();
        }

        private IQueryable<CoreProduct> AccommodationQuery(IQueryable<CoreProduct> query)
            => query = query.OfType<InternalAccommodation>().Include(x => x.PriceDetails);
        private async Task<IReadOnlyList<CoreProduct>> GetCoreProducts(IEnumerable<IProductRequest> requests, int internalPropertyId)
        {
            var query = _dbContext.Products.OfType<CoreProduct>().AsSplitQuery();

            foreach(var request in requests.GroupBy(x => x.GetType(), x => x))
            {
                query = request switch
                {
                    IAccommodationRequest => AccommodationQuery(query),
                    // more types here
                    _ => throw new UnreachableException()
                };
            }

            return await query.Where(x => x.InternalPropertyId == internalPropertyId && requests.Select(x => x.ProductId).Contains(x.Id)).ToListAsync();
        }

        private IQueryable<CoreProduct> AccommodationQuery(IQueryable<CoreProduct> query)
            => query = query.OfType<InternalAccommodation>().Include(x => x.PriceDetails);
C# banner
C#Join
We are a programming server aimed at coders discussing everything related to C# (CSharp) and .NET.
61,871Members
Resources

Similar Threads

Was this page helpful?
Recent Announcements

Similar Threads

❔ Polymorphic relationships in EF Core / .NET Core
C#CC# / help
3y ago
Help with EF Core polymorphic associations
C#CC# / help
2y ago
✅ Ef-core query efficiency?
C#CC# / help
15mo ago
✅ Ef Core unexpected query behaviour
C#CC# / help
17mo ago