3

如何在实体框架 6.1 中duplicate key row with unique index使用属性处理 SqlException ?[Index(IsUnique = true)]

4

2 回答 2

4

所以这里有一个快速破解

try
{
    context.SaveChanges();
}
catch (DbUpdateException e)
{
    SqlException innerException = null;
    Exception tmp = e;
    while(innerException == null && tmp!=null)
    {
        if (tmp != null)
        {
            innerException = tmp.InnerException as SqlException;
            tmp = tmp.InnerException;
        }

    }
    if (innerException != null && innerException.Number == 2601)
    {
        // handle exception
    }
    else
    {
        throw;
    }
}

我希望有更好的解决方案...

于 2014-05-15T08:56:18.357 回答
0

您可以覆盖ValidateEntitydbContext 并在此处执行您的逻辑。

我已经发布了有关如何在 CodeProject 中执行此操作的通用方法

在实体框架中的 dbContext ValidateEntity 处验证唯一约束

于 2016-10-22T09:06:52.397 回答