This query was written in the our system some time ago but the performance of this query is getting poor with a little increase in data. My investigation shows (CodeCount
) where query firing another subquery causing a massive delay in execution. I need to optimize this Linq query. any help will be highly appreciated
from batch in Context.VoucherCodeBatch.ToList()
join type in Context.VoucherCodeType on batch.VoucherTypeId equals type.VoucherTypeId
join voucher in Context.Voucher on batch.VoucherCodeBatchId equals voucher.VoucherCodeBatchId
where batchIds.Contains(batch.BatchCode)
group new
{
batch.BatchCode,
batch.CreationDate,
type.VoucherTypeName,
voucher.AllowedCount,
voucher.ValidFrom,
voucher.ValidTo,
batch.VoucherCodeBatchId,
voucher.VoucherCode
}
by new { batch.BatchCode }
into uniquebatch
select new Batch
{
BatchCode = uniquebatch.FirstOrDefault().BatchCode,
CreationDate = uniquebatch.FirstOrDefault().CreationDate,
TimesAllowed = uniquebatch.FirstOrDefault().AllowedCount,
ValidFrom = uniquebatch.FirstOrDefault().ValidFrom,
CodeCount = ((from c in Context.Voucher.ToList()
where
c.VoucherCodeBatchId ==
uniquebatch.FirstOrDefault().VoucherCodeBatchId
select c).Count()),
ValidTo = uniquebatch.FirstOrDefault().ValidTo,
CodeType = uniquebatch.FirstOrDefault().VoucherTypeName,
VoucherCodeBatchId = uniquebatch.FirstOrDefault().VoucherCodeBatchId
});
ToList()
in there means that this query is requesting all Voucher rows from the database and filters in memory. Try removing it. – Daniel Hilgarth Jun 4 '13 at 11:43