public string UpdateBlockTime(IPS_Invoice model) { string message = ""; // 开启事务 using (IDbContextTransaction dbContextTransaction = iPSContext.Database.BeginTransaction()) { try { if (model.BLOCK) { model.BLOCKTIME = DateTime.Now; } else { model.BLOCKTIME = null; } string UpdateBlockTimeSql = @"UPDATE [dbo].[IPS_Invoice] SET [BLOCK] = @BLOCK,[BLOCKTIME] = @BLOCKTIME WHERE 1 = 1 and [IPS_ID] = @IPS_ID"; int affectedRows = iPSContext.Database.ExecuteSqlRaw(UpdateBlockTimeSql, new SqlParameter("@BLOCK", model.BLOCK), new SqlParameter("@BLOCKTIME", model.BLOCKTIME), new SqlParameter("@IPS_ID", model.IPS_ID)); if (affectedRows > 0) { message = "True"; } else { message = "No records updated"; } //提交事务 dbContextTransaction.Commit(); } catch (Exception e) { message = "False"; //回滚 dbContextTransaction.Rollback(); } } return message; } 直接更新null会报错
时间: 2024-02-10 22:27:09 浏览: 25
根据你提供的代码,使用 `ExecuteSqlRaw` 方法来执行原始 SQL 查询或命令时,将 NULL 值直接传递给参数可能会导致错误。这是因为在 SQL 中,NULL 值需要通过 `DBNull.Value` 来表示。
你可以根据需要修改代码,将 NULL 值转换为 `DBNull.Value`:
```csharp
public string UpdateBlockTime(IPS_Invoice model)
{
string message = "";
// 开启事务
using (IDbContextTransaction dbContextTransaction = iPSContext.Database.BeginTransaction())
{
try
{
if (model.BLOCK)
{
model.BLOCKTIME = DateTime.Now;
}
else
{
model.BLOCKTIME = null;
}
string UpdateBlockTimeSql = @"UPDATE [dbo].[IPS_Invoice] SET [BLOCK] = @BLOCK, [BLOCKTIME] = @BLOCKTIME WHERE [IPS_ID] = @IPS_ID";
SqlParameter blockParam = new SqlParameter("@BLOCK", model.BLOCK);
SqlParameter blockTimeParam = new SqlParameter("@BLOCKTIME", (object)model.BLOCKTIME ?? DBNull.Value);
SqlParameter ipsIdParam = new SqlParameter("@IPS_ID", model.IPS_ID);
int affectedRows = iPSContext.Database.ExecuteSqlRaw(UpdateBlockTimeSql, blockParam, blockTimeParam, ipsIdParam);
if (affectedRows > 0)
{
message = "True";
}
else
{
message = "No records updated";
}
//提交事务
dbContextTransaction.Commit();
}
catch (Exception e)
{
message = "False";
//回滚
dbContextTransaction.Rollback();
}
}
return message;
}
```
在上述代码中,我们使用 `(object)model.BLOCKTIME ?? DBNull.Value` 表示如果 `model.BLOCKTIME` 为 NULL,则将其转换为 `DBNull.Value`。
通过这样的处理,当 `model.BLOCKTIME` 为 NULL 时,可以将 NULL 值正确地传递给 SQL 查询或命令中的参数。请确保在执行 SQL 命令之前,对参数进行适当的类型转换和赋值。
希望这可以解决你遇到的问题。如果还有其他疑问,请随时提问。