从实体框架重复键例外? [英] Duplicate key exception from Entity Framework?

查看:105
本文介绍了从实体框架重复键例外?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图赶上抛出的异常,当我插入与给定用户名的现有用户到我的数据库。正如标题所说那么我用EF。当我尝试对用户插入到数据库是一个UpdateException那抛出的唯一的例外 - 我怎样才能提取该异常来确定其是否重复异常或别的东西。


解决方案

 赶上(UpdateException前)
{
    SQLEXCEPTION的InnerException = ex.InnerException为的SQLException;
    如果(的InnerException = NULL&放大器;!&安培; innerException.Number == ??????)
    {
        //这里处理异常..
    }
    其他
    {
        扔;
    }
}

把正确数量的 ?????? 对应唯一约束冲突(我没有从我的头顶知道)。

I'm trying to catch the exception thrown when I insert a already existing user with the given username into my database. As the title says then I'm using EF. The only exception that's thrown when I try to insert the user into to db is a "UpdateException" - How can I extract this exception to identify whether its a duplicate exception or something else?

解决方案

catch (UpdateException ex)
{
    SqlException innerException = ex.InnerException as SqlException;
    if (innerException != null && innerException.Number == ??????)
    {
        // handle exception here..
    }
    else
    {
        throw;
    }
}

Put the correct number at ?????? that corresponds to unique constraint violation (I don't know it from the top of my head).

这篇关于从实体框架重复键例外?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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