电表历史数据采集:优化代码示例
public async Task<dynamic> ReceiveElectricityMeterHistoryDTONew(dynamic input, DateTime recordTime)
{
var inputList = input.DataList as List<dynamic>;
var json = inputList.ToJson();
_logger.LogInformation('接收电表历史数据:' + json);
decimal totalPower = 0;
var sn = '';
ElectricityMeter_History model = new();
List<KeyValuePair<string, string>> dataList = json.ToList<KeyValuePair<string, string>>();
foreach (var item in dataList)
{
switch (item.Key)
{
case 'SN':
sn = item.Value;
break;
case 'TotalPower':
totalPower = Convert.ToDecimal(item.Value);
break;
default:
SetProperty(model, item.Key, item.Value);
break;
}
}
model.Id = IdHelper.GetId();
model.CreateTime = DateTime.Now;
model.Deleted = false;
model.EquipmentId = sn;
model.RecordTime = recordTime;
model.TotalPower = totalPower;
model.COMMStatus = '正常';
if (model.TotalPower == null || model.TotalPower == 0)
{
_logger.LogError('【电表历史数据采集】电量累计值为0:' + json);
return null;
}
if (string.IsNullOrEmpty(model.EquipmentId))
{
_logger.LogError('【电表历史数据采集】设备Id不能为空!');
return null;
}
var equipment = await (from a in Db.GetIQueryable<Equipment_Info>() where a.Deleted == false && a.Id == model.EquipmentId select a).ToListAsync();
if (equipment.Count == 0)
{
_logger.LogError(string.Format('【电表历史数据采集】设备Id【{0}】不存在设备表中', model.EquipmentId));
return null;
}
var mLast = await Db.GetIQueryable<ElectricityMeter_History>().Where(p => p.Deleted == false && p.EquipmentId == model.EquipmentId).OrderByDescending(p => p.RecordTime).Take(1).FirstOrDefaultAsync();
var elecPrice = await GetElectricityPrice(model.EquipmentId);
if (elecPrice == 0)
{
return null;
}
if (mLast != null)
{
decimal mLastTotalPower = mLast.TotalPower ?? 0;
model.ThisPower = model.TotalPower - mLastTotalPower; //本次电量=累计电量-上一次的累计电量
if (model.TotalPower - mLastTotalPower < 0)
{
_logger.LogError('【电表历史数据采集】累计电量累计值回滚异常:' + json);
model.ThisPower = 0;
//return null;
}
}
else
{
model.ThisPower = model.TotalPower ?? 0;
}
model.ThisElectricityPrice = model.ThisPower * elecPrice;
try
{
int rows = 0;
//insert
rows += await Db.InsertAsync(model);
AjaxResult result = new()
{
ErrorCode = 0,
Success = rows == 1,
Msg = rows == 1 ? '成功!' : '失败!'
};
return result;
}
catch (Exception ex)
{
_logger.LogError('【电表历史数据采集】电表(' + sn + ')表数据发生错误:' + ex.Message);
return null;
}
}
private void SetProperty(object obj, string propertyName, object value)
{
var property = obj.GetType().GetProperty(propertyName);
if (property != null && property.CanWrite)
{
var convertedValue = Convert.ChangeType(value, property.PropertyType);
property.SetValue(obj, convertedValue);
}
}
private async Task<decimal> GetElectricityPrice(string equipmentId)
{
var queryElecPrice = await (from a in Db.GetIQueryable<Equipment_Info>().Where(p => p.Deleted == false && p.Id == equipmentId)
join b in Db.GetIQueryable<Config_ElectricityPrice>() on a.EnterpriseId equals b.EnterpriseId
into tmp
from bb in tmp.DefaultIfEmpty()
where bb.BeginTime.Hours == DateTime.Now.Hour
&& bb.Deleted == false
select new { ElecPrice = bb == null ? 0 : bb.Price }).FirstOrDefaultAsync();
decimal elecPrice = queryElecPrice == null ? 0 : queryElecPrice.ElecPrice;
var queryConfigPrice = await (from a in Db.GetIQueryable<Config_System>()
where a.KeyName == ConfigEnum.ElectricityGeneration_UploadElectricityPrice.ToString() //'ElectricityGeneration_UploadElectricityPrice'
select new { a.Value1 }).FirstOrDefaultAsync();
var queryIsUseElec = await (from a in Db.GetIQueryable<Equipment_Info>()
join b in Db.GetIQueryable<Equipment_UseType>() on a.EquipmentUseTypeId equals b.Id into tmp
from bb in tmp.DefaultIfEmpty()
where a.Deleted == false
&& bb.Deleted == false
&& a.Id == equipmentId
select new { a.Id, UseTypeName = bb == null ? '' : bb.UseTypeName }
).FirstOrDefaultAsync();
if (queryIsUseElec != null && queryIsUseElec.UseTypeName == EquipmentUseType.总并网.ToString())
{
return decimal.Parse(queryConfigPrice.Value1);
}
else
{
return elecPrice;
}
}
优化说明:
- 使用
SetProperty方法将属性赋值的逻辑提取出来,减少重复代码。 - 将获取电价的逻辑提取为一个独立的方法
GetElectricityPrice,提高代码的可读性和可维护性。 - 使用
async和await关键字异步执行数据库操作,提高代码的性能和响应速度。 - 对异常进行捕获和记录,避免程序崩溃。
修改后的代码的主要变化如下:
- 将
switch语句中重复的代码提取到SetProperty方法中。 - 将获取电价的逻辑提取到
GetElectricityPrice方法中。 - 将数据库操作使用
async和await关键字异步执行。 - 对可能出现的异常进行了捕获和记录。
修改后的代码的优势:
- 代码更简洁、可读性更高。
- 代码更易于维护。
- 代码执行速度更快。
- 代码更健壮,不易出现错误。
希望这些修改能够帮助您提高代码的质量!
原文地址: https://www.cveoy.top/t/topic/pZo7 著作权归作者所有。请勿转载和采集!