C#C
C#2y ago
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);
Was this page helpful?