c# - 如何从 SQL Server 2008 错误代码中识别主键重复项?

标签 c# sql-server entity-framework

我想知道我们如何从 C# 中的 SQL Server 错误代码中识别主键重复错误。

举个例子,我有一个C#表单向SQL Server数据库录入数据,当录入数据发生错误时,如何从异常中找出错误原因?

最佳答案

如果你抓到 SqlException然后查看它的编号,编号2627 表示违反唯一约束(包括主键)。

try
{
    // insertion code
}
catch (SqlException ex)
{
    if (ex.Number == 2627)
    {
        //Violation of primary key. Handle Exception
    }
    else throw;
}

MSSQL_ENG002627

This is a general error that can be raised regardless of whether a database is replicated. In replicated databases, the error is typically raised because primary keys have not been managed appropriately across the topology.

关于c# - 如何从 SQL Server 2008 错误代码中识别主键重复项?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15217711/

相关文章:

c# - Fiddler 使 HttpWebRequest/HttpClient 行为意外

entity-framework - 选择数据时排除属性

c# - 没有接口(interface)和抽象的存储库 = 畸变?

sql-server - 阻止查询编辑器更改 SQL Server Management Studio 中的 View

.net - 使用非常长(10000+ 个字符)的字符串作为 SqlParameter 值

c# - 使用 EF 将数据插入 SQL 数据库

c# - 使用 linq 的 WPF 组合框绑定(bind)

c# - 从 C++ 库中的函数返回数组到 C# 程序

c# - Ajax 幻灯片放映扩展器不起作用

SQL 查询 If not null, then update or else keep the same data