Sin*_*YAS 44 c# sql-server exception-handling unique-key entity-framework-6
我的一个表有一个唯一的密钥,当我尝试插入一个重复的记录时,它会按预期抛出异常.但我需要区分唯一的密钥异常,以便我可以为唯一的密钥约束违规自定义错误消息.
我发现所有的解决方案在网上提出投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.";
}
}
Run Code Online (Sandbox Code Playgroud)
但问题是,铸造ex.InnerException
到System.Data.SqlClient.SqlException
原因无效的转换错误,因为ex.InnerException
实际上是一个类型的System.Data.Entity.Core.UpdateException
,不是System.Data.SqlClient.SqlException
.
上面的代码有什么问题?如何捕获Unique Key Constraint违规?
ken*_*n2k 59
使用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...
}
Run Code Online (Sandbox Code Playgroud)
正如您所提到的UpdateException
,我假设您正在使用ObjectContext
API,但它应该是类似的.
Shi*_*mmy 13
就我而言,我正在使用EF 6并在我的模型中修饰其中一个属性:
[Index(IsUnique = true)]
Run Code Online (Sandbox Code Playgroud)
为了捕获违规行为,我使用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();
}
Run Code Online (Sandbox Code Playgroud)
请注意,这只会捕获唯一的索引约束违规.
我认为显示一些代码可能很有用,不仅可以处理重复行异常,还可以提取一些可用于编程目的的有用信息。例如撰写自定义消息。
该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;
}
}
Run Code Online (Sandbox Code Playgroud)
该类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
}
Run Code Online (Sandbox Code Playgroud)
// 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
}
}
Run Code Online (Sandbox Code Playgroud)
编辑:
您也可以只检查异常的消息组件.像这样的东西:
if (ex.Message.Contains("UniqueConstraint")) // do stuff
Run Code Online (Sandbox Code Playgroud)
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
}
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
42634 次 |
最近记录: |