如何使用 EF6 和 SQL 服务器捕获 UniqueKey Violation 异常?

How can I catch UniqueKey Violation exceptions with EF6 and SQL Server?

我的一个表有一个唯一键,当我尝试插入重复记录时,它会按预期抛出异常。但是我需要将唯一键异常与其他异常区分开来,以便我可以自定义违反唯一键约束的错误消息。

我在网上找到的所有解决方案都建议将 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

上面的代码有什么问题?我怎样才能发现违反唯一键约束的情况?

// 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

使用 EF6 和 DbContext API(对于 SQL 服务器),我目前正在使用这段代码:

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,但它应该是相似的。

如果你想捕获唯一约束

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 
   } 
}

就我而言,我使用的是 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();
}

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

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
    }
}

我认为展示一些代码可能会很有用,不仅可以处理重复行异常,还可以提取一些可用于编程目的的有用信息。例如。编写自定义消息。

Exception subclass 使用正则表达式提取数据库 table 名称、索引名称和键值。

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 class 很容易使用...只需像以前的答案一样创建一些错误处理代码...

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
}

SQL 服务器的错误消息可以用这个语句捕获。

try
 {
     //trying to insert unique key data      
 }
 catch (Exception ex)
 {
    var exp = ((SqlException)ex.InnerException.InnerException).Message;
    // exp hold error message generated by sql
 }

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

     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); }
     }

我刚刚更新了上面的代码,它对我有用。