如何使用EF6和SQL Server捕获唯一键冲突异常?

74

我的一个表具有唯一键,当我尝试插入重复记录时,它会像预期的那样抛出异常。但是我需要区分唯一键异常和其他异常,以便我可以为唯一键约束违规自定义错误消息。

我在网上找到的所有解决方案都建议将ex.InnerException转换为System.Data.SqlClient.SqlException,并检查Number属性是否等于2601或2627,如下所示:

try
{
    _context.SaveChanges();
}
catch (Exception ex)
{
    var sqlException = ex.InnerException as System.Data.SqlClient.SqlException;

    if (sqlException.Number == 2601 || sqlException.Number == 2627)
    {
        ErrorMessage = "Cannot insert duplicate values.";
    }
    else
    {
        ErrorMessage = "Error while saving data.";
    }
}

但问题是,将ex.InnerException转换为System.Data.SqlClient.SqlException会导致无效的强制类型转换错误,因为ex.InnerException实际上是System.Data.Entity.Core.UpdateException类型,而不是System.Data.SqlClient.SqlException

上面的代码有什么问题?如何捕获唯一键约束冲突?

7个回答

84

使用EF6和DbContext API(针对SQL Server),我目前正在使用以下代码:

try
{
  // Some DB access
}
catch (Exception ex)
{
  HandleException(ex);
}

public virtual void HandleException(Exception exception)
{
  if (exception is DbUpdateConcurrencyException concurrencyEx)
  {
    // A custom exception of yours for concurrency issues
    throw new ConcurrencyException();
  }
  else if (exception is DbUpdateException dbUpdateEx)
  {
    if (dbUpdateEx.InnerException != null
            && dbUpdateEx.InnerException.InnerException != null)
    {
      if (dbUpdateEx.InnerException.InnerException is SqlException sqlException)
      {
        switch (sqlException.Number)
        {
          case 2627:  // Unique constraint error
          case 547:   // Constraint check violation
          case 2601:  // Duplicated key row error
                      // Constraint violation exception
            // A custom exception of yours for concurrency issues
            throw new ConcurrencyException();
          default:
            // A custom exception of yours for other DB issues
            throw new DatabaseAccessException(
              dbUpdateEx.Message, dbUpdateEx.InnerException);
        }
      }

      throw new DatabaseAccessException(dbUpdateEx.Message, dbUpdateEx.InnerException);
    }
  }

  // If we're here then no exception has been thrown
  // So add another piece of code below for other exceptions not yet handled...
}

根据您提到的UpdateException,我假设您正在使用ObjectContext API,但它应该是类似的。


2
有没有办法检测违规发生在哪一列?一个表中可能有多个唯一键... - Learner
@Learner 我能想到的唯一方法是解析错误消息(其中列出了约束/列的名称),但这不是一个很好的解决方案(错误消息可能会在未来更新,更重要的是,它们被翻译成多种语言)。 - ken2k
2
这难道不会破坏ORM的模式,直接创建到数据库的依赖关系吗?这是否意味着每次我使用其他数据库时都必须重新编写异常处理以识别特定的代码? - Daniel Lobo
2
@ken2k 这份代码依赖于SQL Server的实现,无法在其他数据库上运行。正如Daniel Lobo所提到的那样,它破坏了ORM的理念。 - Tomas
4
我在想有多少人曾经将他们的应用程序完全迁移到另一个数据库系统?我已经编程30年了,我们从未将应用程序迁移到不同的数据库系统。 - LarryBud
显示剩余5条评论

32

在我的情况下,我正在使用EF 6,并在我的模型中的一个属性上进行了修饰:

[Index(IsUnique = true)]

为了捕获违规行为,我使用C# 7执行以下操作,这样做变得更加容易:

protected async Task<IActionResult> PostItem(Item item)
{
  _DbContext.Items.Add(item);
  try
  {
    await _DbContext.SaveChangesAsync();
  }
  catch (DbUpdateException e)
  when (e.InnerException?.InnerException is SqlException sqlEx && 
    (sqlEx.Number == 2601 || sqlEx.Number == 2627))
  {
    return StatusCode(StatusCodes.Status409Conflict);
  }

  return Ok();
}

请注意,这只会捕获唯一索引约束的违规情况。


9
try
{
   // do your insert
}
catch(Exception ex)
{
   if (ex.GetBaseException().GetType() == typeof(SqlException))
   {
       Int32 ErrorCode = ((SqlException)ex.InnerException).Number;
       switch(ErrorCode)
       {
          case 2627:  // Unique constraint error
              break;
          case 547:   // Constraint check violation
              break;
          case 2601:  // Duplicated key row error
              break;
          default:
              break;
        }
    }
    else
    {
       // handle normal exception
    }
}

2
我喜欢这个功能能添加额外的错误代码,switch 语句使代码看起来更清晰,但我认为你在将 InnerException 强制转换为 ErrorCode 时存在小错误。我认为你想使用 GetBaseException() 而不是使用 InnerException。 - Steve Haselschwerdt
此外,这会吞噬所有的 SqlException 类型,而不仅仅是唯一键冲突。我认为你的 default 情况可能应该重新抛出异常。 - Steve Haselschwerdt

7
// put this block in your loop
try
{
   // do your insert
}
catch(SqlException ex)
{
   // the exception alone won't tell you why it failed...
   if(ex.Number == 2627) // <-- but this will
   {
      //Violation of primary key. Handle Exception
   }
}

编辑:

你也可以检查异常的消息组件。像这样:

if (ex.Message.Contains("UniqueConstraint")) // do stuff

3
不幸的是,catch(SqlException ex)无法捕获唯一键冲突异常,并抛出此错误:类型为'System.Data.Entity.Infrastructure.DbUpdateException'的异常在EntityFramework.dll中发生,但未在用户代码中处理。 - Sinan ILYAS
检查错误消息中的“UniqueConstraint”应该可以解决问题,但这似乎不是最佳方法。 - Sinan ILYAS

7

我认为展示一些处理重复行异常的代码并提取一些有用信息可能会很有用,这些信息可用于编程目的。例如:组成自定义消息。

这个Exception子类使用正则表达式提取数据库表名、索引名和关键值。

public class DuplicateKeyRowException : Exception
{
    public string TableName { get; }
    public string IndexName { get; }
    public string KeyValues { get; }

    public DuplicateKeyRowException(SqlException e) : base(e.Message, e)
    {
        if (e.Number != 2601) 
            throw new ArgumentException("SqlException is not a duplicate key row exception", e);

        var regex = @"\ACannot insert duplicate key row in object \'(?<TableName>.+?)\' with unique index \'(?<IndexName>.+?)\'\. The duplicate key value is \((?<KeyValues>.+?)\)";
        var match = new System.Text.RegularExpressions.Regex(regex, System.Text.RegularExpressions.RegexOptions.Compiled).Match(e.Message);

        Data["TableName"] = TableName = match?.Groups["TableName"].Value;
        Data["IndexName"] = IndexName = match?.Groups["IndexName"].Value;
        Data["KeyValues"] = KeyValues = match?.Groups["KeyValues"].Value;
    }
}

DuplicateKeyRowException类很容易使用...只需创建一些错误处理代码,就像以前的答案一样...

public void SomeDbWork() {
    // ... code to create/edit/update/delete entities goes here ...
    try { Context.SaveChanges(); }
    catch (DbUpdateException e) { throw HandleDbUpdateException(e); }
}

public Exception HandleDbUpdateException(DbUpdateException e)
{
    // handle specific inner exceptions...
    if (e.InnerException is System.Data.SqlClient.SqlException ie)
        return HandleSqlException(ie);

    return e; // or, return the generic error
}

public Exception HandleSqlException(System.Data.SqlClient.SqlException e)
{
    // handle specific error codes...
    if (e.Number == 2601) return new DuplicateKeyRowException(e);

    return e; // or, return the generic error
}

4

如果您想捕获唯一约束

try { 
   // code here 
} 
catch(Exception ex) { 
   //check for Exception type as sql Exception 
   if(ex.GetBaseException().GetType() == typeof(SqlException)) { 
     //Violation of primary key/Unique constraint can be handled here. Also you may //check if Exception Message contains the constraint Name 
   } 
}

0

编写代码时必须非常具体。

     try
     {
         // do your stuff here.
     {
     catch (Exception ex)
     {
         if (ex.Message.Contains("UNIQUE KEY"))
         { 
            Master.ShowMessage("Cannot insert duplicate Name.", MasterSite.MessageType.Error);
         }
         else { Master.ShowMessage(ex.Message, MasterSite.MessageType.Error); }
     }

我刚刚稍微更新了上面的代码,现在它可以正常工作了。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接