public async Task<pms_plan> UpdateOrder(string plaSsn, string direction) { if (string.IsNullOrEmpty(plaSsn) || string.IsNullOrEmpty(direction)) { return null!; } var plsn = await _sqlSugarClient.Queryable<pms_plan>().FirstAsync(s => s.sn == plaSsn); if (plsn == null) { return null!; } var PendingList = await _sqlSugarClient.Queryable<pms_plan>() .OrderBy(it => new { it.plan_date, it.list_order }) .ToListAsync(); int inden = PendingList.FindIndex(i => i.sn == plsn.sn); if (direction == "up") { var plan1 = PendingList[inden - 1]; int i = 0; i = (int)plan1.list_order!; plan1.list_order = plsn.list_order; plsn.list_order = i; _sqlSugarClient.Updateable(plan1).WhereColumns(it => new { it.id }).ExecuteCommand();//更新单 条根据ID } if (direction == "down") { var plan1 = PendingList[inden + 1]; int i = 0; i = (int)plan1.list_order!; plan1.list_order = plsn.list_order; plsn.list_order = i; _sqlSugarClient.Updateable(plan1).WhereColumns(it => new { it.id }).ExecuteCommand();//更新单 条根据ID } _sqlSugarClient.Updateable(plsn).WhereColumns(it => new { it.id }).ExecuteCommand();//更新单 条根据ID return plsn; }优化代码
时间: 2023-03-31 22:04:52 浏览: 145
这是一段 C# 代码,用于更新数据库中的 pms_plan 表中的记录的顺序。如果传入的参数 plaSsn 或 direction 为空,则返回 null。如果找不到与 plaSsn 相匹配的记录,则也返回 null。如果 direction 为 "up",则将该记录与前一条记录的顺序互换;如果 direction 为 "down",则将该记录与后一条记录的顺序互换。最后,更新该记录的顺序,并返回该记录。
对于这段代码,可以进行如下优化:
1. 首先,可以将查询数据库的操作放在一个事务中,以提高效率和数据一致性。
2. 其次,可以使用异步操作来提高代码的性能。
3. 可以使用 LINQ 表达式来简化代码,使其更易读、易懂。
4. 可以使用更加严谨的类型检查和异常处理,以提高代码的健壮性和可维护性。
下面是优化后的代码:
public async Task<pms_plan> UpdateOrder(string plaSsn, string direction)
{
if (string.IsNullOrEmpty(plaSsn) || string.IsNullOrEmpty(direction))
{
return null;
}
using (var tran = await _sqlSugarClient.Ado.BeginTranAsync())
{
try
{
var plsn = await _sqlSugarClient.Queryable<pms_plan>().FirstAsync(s => s.sn == plaSsn);
if (plsn == null)
{
return null;
}
var PendingList = await _sqlSugarClient.Queryable<pms_plan>()
.OrderBy(it => new { it.plan_date, it.list_order })
.ToListAsync();
int inden = PendingList.FindIndex(i => i.sn == plsn.sn);
if (direction == "up")
{
if (inden > )
{
var plan1 = PendingList[inden - 1];
int i = (int)plan1.list_order!;
plan1.list_order = plsn.list_order;
plsn.list_order = i;
await _sqlSugarClient.Updateable(plan1).WhereColumns(it => new { it.id }).ExecuteCommandAsync();
}
}
else if (direction == "down")
{
if (inden < PendingList.Count - 1)
{
var plan1 = PendingList[inden + 1];
int i = (int)plan1.list_order!;
plan1.list_order = plsn.list_order;
plsn.list_order = i;
await _sqlSugarClient.Updateable(plan1).WhereColumns(it => new { it.id }).ExecuteCommandAsync();
}
}
await _sqlSugarClient.Updateable(plsn).WhereColumns(it => new { it.id }).ExecuteCommandAsync();
await tran.CommitAsync();
return plsn;
}
catch (Exception ex)
{
await tran.RollbackAsync();
throw ex;
}
}
}
阅读全文