如何处理Entity Framework上的UpdateException-“违反PRIMARY KEY约束"? [英] How do I handle UpdateException - 'Violation of PRIMARY KEY constraint' on Entity Framework?

查看:48
本文介绍了如何处理Entity Framework上的UpdateException-“违反PRIMARY KEY约束"?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个允许多个用户使用的应用程序和一个具有2个ID作为复合键的数据库表.这些ID也是来自另一个表的外键.因此,当2个用户尝试将具有相同ID的条目添加到此表中时,其中一个由于主键约束违反而获得UpdateException.我已经发现应该这样处理:

I have an appication that allows multiple users and a database table which has 2 IDs as a compound key. These IDs are also foreign keys from another table. So when 2 users try to add an entry to this tabel with the same IDs one of them gets an UpdateException because of Primary Key constaint violation. I already found out that it should be handled like this:

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

但是我实际上在"//Handle here"部分上做什么.我尝试刷新对象,但是它处于已添加"状态,因此无法刷新.我想做的是:确认已经有一个具有这些ID的对象,删除要插入的对象并从数据库中加载现有对象.我该怎么办?

But what do I actually do on the "//Handle here" part. I tried refreshing the object but it is in the "Added" state and therefor can not be refreshed. What I whant it to do is: Acknowledge that there is already an object with these IDs, drop its object that it wanted to insert and load the existing object from the database. How can I do that?

推荐答案

自从我获得赞成票以来,我就回顾了如何解决这个问题.所以这就是我所做的:

Since I got an upvote I looked back how I solved this. So here is what I did:

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


请注意,从EF 4.1开始, UpdateException 已重命名为 DbUpdateException .

Note that UpdateException has been renamed to DbUpdateException starting with EF 4.1.

这篇关于如何处理Entity Framework上的UpdateException-“违反PRIMARY KEY约束"?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆