这个查询是前段时间在我们的系统中编写的,但是随着数据的一点点增加,这个查询的性能变得很差。我的调查显示 ( CodeCount
) 查询触发另一个子查询导致执行的大量延迟。我需要优化这个 Linq 查询。任何帮助将不胜感激
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
});