优化后的LINQ查询如下:

var q = (from a in GetIQueryable() where a.Deleted == false join b in Db.GetIQueryable<Equipment_Info>() on a.EquipmentId equals b.Id into tmp1 from bb in tmp1.DefaultIfEmpty() where bb.EnterpriseId == _operator.EnterpriseId join c in Db.GetIQueryable<Equipment_Type>() on bb.EquipmentTypeId equals c.Id into tmp2 from cc in tmp2.DefaultIfEmpty() select new { a.Id, a.RecordTime, a.EquipmentId, bb.EquipmentName, bb.EquipmentTypeId, cc.TypeName, a.Remarks, a.AlarmTime, a.AlarmCode, a.AlarmLevel, a.AlarmDescription, a.AlarmValue, a.AlarmCount, a.AlamType, AlamTypeName = a.AlamType == 0 ? '报警' : '故障', a.SolveState, SolveStateName = a.SolveState == 0 ? '待处理' : '已处理', a.SolveUser, a.SolveTime, a.SolveResult, }) .Union ( from a in GetIQueryable() where a.Deleted == false join b in Db.GetIQueryable<Equipment_ChargingPileInfo>() on a.EquipmentId equals b.Id into tmp1 from bb in tmp1.DefaultIfEmpty() where bb.EnterpriseId == _operator.EnterpriseId select new { a.Id, a.RecordTime, a.EquipmentId, bb.EquipmentName, EquipmentTypeId = 'cdz', TypeName = EquipmentType.充电桩.ToString(), a.Remarks, a.AlarmTime, a.AlarmCode, a.AlarmLevel, a.AlarmDescription, a.AlarmValue, a.AlarmCount, a.AlamType, AlamTypeName = a.AlamType == 0 ? '报警' : '故障', a.SolveState, SolveStateName = a.SolveState == 0 ? '待处理' : '已处理', a.SolveUser, a.SolveTime, a.SolveResult, } ) .Union ( from a in GetIQueryable() where a.Deleted == false join b in Db.GetIQueryable<Equipment_ChargingGunsInfo>() on a.EquipmentId equals b.Id into tmp1 from bb in tmp1.DefaultIfEmpty() join c in Db.GetIQueryable<Equipment_ChargingPileInfo>() on bb.ChargingPileId equals c.Id into tmp2 from cc in tmp2.DefaultIfEmpty() where cc.EnterpriseId == _operator.EnterpriseId select new { a.Id, a.RecordTime, a.EquipmentId, bb.EquipmentName, EquipmentTypeId = 'cdq', TypeName = EquipmentType.充电枪.ToString(), a.Remarks, a.AlarmTime, a.AlarmCode, a.AlarmLevel, a.AlarmDescription, a.AlarmValue, a.AlarmCount, a.AlamType, AlamTypeName = a.AlamType == 0 ? '报警' : '故障', a.SolveState, SolveStateName = a.SolveState == 0 ? '待处理' : '已处理', a.SolveUser, a.SolveTime, a.SolveResult, });

在优化后的查询中,我们首先将 where 语句放置在 join 语句之前,这样可以更早地过滤掉不必要的记录,从而提高查询效率。另外,我们还将一些重复的代码合并,使代码更简洁易读。

通过这些优化,我们可以显著提高 LINQ 查询的性能和可读性。


原文地址: https://www.cveoy.top/t/topic/pq7e 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录