我想知道我们如何从 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;
}
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/