c# - 如何在 C# 中违反约束的异常中获取列名称

标签 c# sql-server constraints

我对货币字段有限制,不能接受负值。约束一切正常,当违反约束时,我会收到错误,如下所示。

Unable to update row. Reason: The UPDATE statement conflicted with the CHECK constraint "CK_Product_StandardCost". The conflict occurred in database "AdventureWorksLT", table "SalesLT.Product", column 'StandardCost'. The statement has been terminated.

我在 catch block 中收到此错误,因为我正在更新表中的不正确数据。

enter image description here

我想要的是在特定的此约束触发时获取列名称。这里是:StandardCost。有什么方法可以在我的 C# 代码中找到列名称吗?

最佳答案

异常消息上带有 IndexOf 的简单 Substring:

var message = ex.Message;
var column = message.Substring(message.IndexOf("column '") + 8, message.IndexOf("'", message.IndexOf("column '") + 9) - message.IndexOf("column '") - 8);    

关于c# - 如何在 C# 中违反约束的异常中获取列名称,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45736821/

相关文章:

sql-server - 释放对执行流程任务中使用的变量的锁定 | SSIS

sql - 用逗号或 "AND"连接数据库表列的所有值

sql-server - 将包含 "id,attribute,value"列的表转换为 "id,attribute1,attribute2,..."

c# - Moq 一个具体的类方法调用

c# - 如何在不装箱的情况下检索枚举的哈希码?

database - ORM 和数据库约束

mysql - 无法添加外键约束 - 数据类型匹配

sql - Postgres中判断约束名称是否为系统生成

c# - 从 ConstantExpression 获取值

c# - 具有 IEnumerable<ISomeInterface> 类型属性的 NewtonSoft.Json 序列化和反序列化类