Is there any way I can rewrite this piece of code so that I don’t have to duplicate the join and where clauses in multiple queries?
if (categoryId > 0)
{
query = from p in _productRepository.Table
from pv in p.ProductVariants.DefaultIfEmpty()
from pc in p.ProductCategories.Where(pc => pc.CategoryId == categoryId)
join psa in _productSpecificationAttributeRepository.Table on p.Id equals psa.ProductId
join sao in _specificationAttributeOptionRepository.Table on psa.SpecificationAttributeOptionId equals sao.Id
join sa in _specificationAttributeRepository.Table on sao.SpecificationAttributeId equals sa.Id
where p.Published && pv.Published && !p.Deleted && psa.AllowFiltering &&
(!pv.AvailableStartDateTimeUtc.HasValue || pv.AvailableStartDateTimeUtc.Value < nowUtc) &&
(!pv.AvailableEndDateTimeUtc.HasValue || pv.AvailableEndDateTimeUtc.Value > nowUtc)
select new {sa, sao};
}
else if (brandId > 0)
{
query = from p in _productRepository.Table
from pv in p.ProductVariants.DefaultIfEmpty()
from pb in p.ProductBrands.Where(pb => pb.BrandId == brandId)
join psa in _productSpecificationAttributeRepository.Table on p.Id equals psa.ProductId
join sao in _specificationAttributeOptionRepository.Table on psa.SpecificationAttributeOptionId equals sao.Id
join sa in _specificationAttributeRepository.Table on sao.SpecificationAttributeId equals sa.Id
where p.Published && pv.Published && !p.Deleted && psa.AllowFiltering &&
(!pv.AvailableStartDateTimeUtc.HasValue || pv.AvailableStartDateTimeUtc.Value < nowUtc) &&
(!pv.AvailableEndDateTimeUtc.HasValue || pv.AvailableEndDateTimeUtc.Value > nowUtc)
select new {sa, sao};
}
//only distinct attributes (group by ID)
query = from x in query
group x by x.sao.Id into xGroup
orderby xGroup.Key
select xGroup.FirstOrDefault();
The only thing that changes between the 2 queries is this join:
from pc in p.ProductCategories.Where(pc => pc.CategoryId == categoryId)
with this join:
from pb in p.ProductBrands.Where(pb => pb.BrandId == brandId)
After a good night’s sleep i came up with the solution, which is very simple – split the query in 2 parts: