Der*_*ler 6 c# sql entity-framework
我有一个允许多个用户的应用程序和一个具有2个ID作为复合键的数据库表.这些ID也是来自另一个表的外键.因此,当2个用户尝试使用相同的ID向此tabel添加条目时,由于主键违反规则,其中一个用户会获得UpdateException.我已经发现它应该像这样处理:
try
{
result = base.SaveChanges(options);
}
catch (UpdateException ex)
{
SqlException innerException = ex.InnerException as SqlException;
if (innerException != null && innerException.Number == 2627 || innerException.Number == 2601)
{
// handle here
}
else
{
throw;
}
}
Run Code Online (Sandbox Code Playgroud)
但是我在"// Handle here"部分实际上做了什么.我尝试刷新对象,但它处于"已添加"状态,因此无法刷新.我要做的是:确认已经存在具有这些ID的对象,删除它想要插入的对象并从数据库加载现有对象.我怎样才能做到这一点?
自从我得到了赞成票后,我回顾了我是如何解决这个问题的。所以这就是我所做的:
// Exception number 2627 = Violation of %ls constraint '%.*ls'. Cannot insert duplicate key in object '%.*ls'.
// Exception number 2601 = Cannot insert duplicate key row in object '%.*ls' with unique index '%.*ls'.
// See http://msdn.microsoft.com/en-us/library/cc645603.aspx for more information and possible exception numbers
if (innerException != null && (innerException.Number == 2627 || innerException.Number == 2601))
{
// Resolve the primary key conflict by refreshing and letting the store win
// In order to be able to refresh the entity its state has to be changed from Added to Unchanged
ObjectStateEntry ose = ex.StateEntries.Single();
this.ObjectStateManager.ChangeObjectState(ose.Entity, EntityState.Unchanged);
base.Refresh(RefreshMode.StoreWins, ose.Entity);
// Refresh addedChanges now to remove the refreshed entry from it
addedChanges = this.ObjectStateManager.GetObjectStateEntries(System.Data.EntityState.Added).Where(s => !s.IsRelationship);
}
else
{
throw;
}
Run Code Online (Sandbox Code Playgroud)
编辑:
请注意,从 EF 4.1 开始UpdateException已重命名DbUpdateException。