直接上代码分析,以下代码中全部使用join关联多表,其中BarCodeRelation表有1700万笔数据;执行以下语句获取某个月的数据,大概10分钟左右,对B/S程序1~3秒的响应,根本在前端展示不出数据。
var query = from pd in _dbContext.ProductDetail
join p in _dbContext.Product on pd.Product equals p.Id
join o in _dbContext.Orders on p.OwnerOrder equals o.Id
join od in _dbContext.OrderDetail on p.OrderDetail equals od.Id
join pc in _dbContext.ProductColor on od.ProductColor equals pc.Id
join bcr in _dbContext.BarCodeRelation on pd.Product equals bcr.ProductId
join pct in _dbContext.ProductComponent.Where(q=>(string.IsNullOrEmpty(begindate) || q.Create_Date >= begindt) && (string.IsNullOrEmpty(enddate) || q.Create_Date <= enddt))
on bcr.Child equals pct.Id
join wed in _dbContext.WarehousingEntryDetail on pct.WarehousingEntryDetail equals wed.Id
join pci in _dbContext.ProductComponentInfo.Where(q=> q.Name == "电子序列号" ) on wed.ProductComponentInfo equals pci.Id
orderby pd.Id
where (string.IsNullOrEmpty(model) || o.Model.Contains(model)) && (pci.Name == "电子序列号")
select new SNListModel
{
Model = o.Model,
Name = pc.Name,
ProductBarCode = pd.ProductBarCode,
BarCode = pct.BarCode
};
经过优化代码,改用Left join、Left join子查询、及主表下日期过滤条件的方式,如下:
var query = from pd in _dbContext.ProductDetail.Where(q => (string.IsNullOrEmpty(begindate) || q.Create_Date >= begindt) && (string.IsNullOrEmpty(enddate) || q.Create_Date <= enddt))
join p in _dbContext.Product on pd.Product equals p.Id into p1 from p12 in p1.DefaultIfEmpty()
join o in _dbContext.Orders on p12.OwnerOrder equals o.Id into o1 from o12 in o1.DefaultIfEmpty()
join od in _dbContext.OrderDetail on p12.OrderDetail equals od.Id into od1 from od12 in od1.DefaultIfEmpty()
join ct in _dbContext.Customer on o12.Customer equals ct.Id into ct1 from ct12 in ct1.DefaultIfEmpty()
join pc in _dbContext.ProductColor on od12.ProductColor equals pc.Id into pc1 from pc12 in pc1.DefaultIfEmpty()
join sq in (from bcr in _dbContext.BarCodeRelation
join pctb in _dbContext.ProductComponent on bcr.Child equals pctb.Id
join wedb in _dbContext.WarehousingEntryDetail on pctb.WarehousingEntryDetail equals wedb.Id
join pcib in _dbContext.ProductComponentInfo.Where(q => q.Name == "电子序列号") on wedb.ProductComponentInfo equals pcib.Id
select new ProductBarcodeModel
{
ProductId = bcr.ProductId,
BarCode = pctb.BarCode,
Code = pcib.Code,
Name = pcib.Name
}) on pd.Product equals sq.ProductId into sq1 from sq12 in sq1.DefaultIfEmpty()
orderby o12.Model, pc12.Name, pd.ProductBarCode
where (string.IsNullOrEmpty(model) || o12.Model.Contains(model)) && !string.IsNullOrEmpty(sq12.BarCode)
select new SNListModel
{
Model = o12.Model,
Name = pc12.Name,
ProductBarCode = pd.ProductBarCode,
BarCode = sq12.BarCode
};
这么调整后,查询某个月的数据,响应速度在1~2秒之内;