C# 在实体框架4中处理异常

C# 在实体框架4中处理异常,c#,sql,entity-framework,C#,Sql,Entity Framework,我需要一种使用实体框架LINQ来区分SQL异常的方法,例如,当我从DbUpdateException得到的只是大量嵌套的内部异常和无用的长错误消息时,如何区分foreing键约束冲突和unique约束冲突?是否有任何较低级别的异常,我可以在其中执行类似“Catch FKException”的操作;捕获“uniqueException”或类似内容。试试看 try { //code }

我需要一种使用实体框架LINQ来区分SQL异常的方法,例如,当我从DbUpdateException得到的只是大量嵌套的内部异常和无用的长错误消息时,如何区分foreing键约束冲突和unique约束冲突?是否有任何较低级别的异常,我可以在其中执行类似“Catch FKException”的操作;捕获“uniqueException”或类似内容。

试试看
            try
            {
                //code
            }
            catch (System.Data.Entity.Validation.DbEntityValidationException e)
            {
                string rs = "";
                foreach (var eve in e.EntityValidationErrors)
                {
                    rs = string.Format("Entity of type \"{0}\" in state \"{1}\" has the following validation errors:", eve.Entry.Entity.GetType().Name, eve.Entry.State);
                    Console.WriteLine(rs);

                    foreach (var ve in eve.ValidationErrors)
                    {
                        rs += "<br />" + string.Format("- Property: \"{0}\", Error: \"{1}\"", ve.PropertyName, ve.ErrorMessage);
                    }
                }
                throw new Exception(rs);
            }
{ //代码 } 捕获(System.Data.Entity.Validation.DbEntityValidationException e) { 字符串rs=“”; foreach(e.EntityValidationErrors中的变量eve) { rs=string.Format(“状态为“{1}\”的类型为“{0}\”的实体存在以下验证错误:”,eve.Entry.Entity.GetType().Name,eve.Entry.state); 控制台写入线(rs); foreach(eve.ValidationErrors中的变量ve) { rs+=“
”+string.Format(“-Property:\“{0}\”,错误:\“{1}\”,ve.PropertyName,ve.ErrorMessage); } } 抛出新异常(rs); }
使用sql错误代码

catch (DbUpdateException ex)
                    {
                        var sqlex = ex.InnerException.InnerException as SqlException;

                        if (sqlex != null)
                        {
                            switch (sqlex.Number)
                            {
                                case 547: throw new ExNoExisteUsuario("No existe usuario destino."); //FK exception
                                case 2627:
                                case 2601:
                                    throw new ExYaExisteConexion("Ya existe la conexion."); //primary key exception

                                default: throw sqlex; //otra excepcion que no controlo.


                            }
                        }

                        throw ex;
                    }

我为此编写了两个实用程序方法:

public static class DbUtils
{
    /// <summary>
    ///     Takes a code block that updates database, runs it and catches db exceptions. If the caught
    ///     exception is one of those that are ok to ignore (okToIgnoreChecks) then no
    ///     exception is raised and result is returned. Otherwise an exception is rethrown.
    /// 
    ///     This function is intended to be run within an explicit transaction, i.e.:
    ///     using (var transaction = db.Database.BeginTransaction()), which should be committed/rolledback afterwards.
    ///     Otherwise, if you don't use a transaction discard the db context or in other words make this operation
    ///     the only one that you run within implicit transaction.
    /// 
    ///     This function can wrap a single DB statement, but it's more efficient to wrap multiple statements
    ///     so that locks are held for shorter period of time.
    ///     If an exception occurs within a transaction and is caught by this function, all other changes
    ///     will be still saved to DB on commit if transaction is used.
    /// </summary>
    /// <typeparam name="T">Any result returned by the code block</typeparam>
    /// <param name="context">Database connection</param>
    /// <param name="dbCodeBlock">
    ///     Code block to execute that updates DB. It's expected, but not critical that
    ///     this code does not throw any other exceptions. Do not call SaveChanges() from the code block itself. Let this
    ///     function do it for you.
    /// </param>
    /// <param name="okToIgnoreChecks">
    ///     List of functions that will check if an exception can be ignored.
    /// </param>
    /// <returns>Returns number of rows affected in DB and result produced by the code block</returns>
    public static Tuple<int, T> IgnoreErrors<T>(DbContext context,
        Func<T> dbCodeBlock, params Func<DbUpdateException, bool>[] okToIgnoreChecks)
    {
        var result = dbCodeBlock();
        try
        {
            var rowsAffected = context.SaveChanges();
            return Tuple.Create(rowsAffected, result);
        }
        catch (DbUpdateException e)
        {
            if (okToIgnoreChecks.Any(check => check(e)))
                return Tuple.Create(0, result);
            throw;
        }
    }

    public static bool IsDuplicateInsertError(DbUpdateException e)
    {
        return GetErrorCode(e) == 2601;
    }

    public static bool IsForeignKeyError(DbUpdateException e)
    {
        return GetErrorCode(e) == 547;
    }

    public static T UpdateEntity<T>(DbContext context, T entity, Action<T> entityModifications)
        where T : class
    {
        return EntityCrud(context, entity, (db, e) =>
        {
            db.Attach(e);
            entityModifications(e);
            return e;
        });
    }

    public static T DeleteEntity<T>(DbContext context, T entity)
        where T : class
    {
        return EntityCrud(context, entity, (db, e) => db.Remove(e));
    }

    public static T InsertEntity<T>(DbContext context, T entity)
        where T : class
    {
        return EntityCrud(context, entity, (db, e) => db.Add(e));
    }

    public static T EntityCrud<T>(DbContext context, T entity, Func<DbSet<T>, T, T> crudAction)
        where T : class
    {
        return crudAction(context.Set<T>(), entity);
    }
}
不会引发任何异常

与前面的示例类似,但显式处理FK冲突异常:

        try
        {
            var numInserted = DbUtils.IgnoreErrors(_db, () => DbUtils.InsertEntity(_db, someEntity), DbUtils.IsDuplicateInsertError).Item1;
            // no FK exception, but maybe unique index violation, safe
            // to keep going with transaction
        }
        catch (DbUpdateException e)
        {
            if (DbUtils.IsForeignKeyError(e))
            {
              // you know what to do
            }
            throw; // rethrow other db errors
        }

最终,如果您有显式事务,您可以调用commit transaction,否则已在上下文中调用save。

通常内部异常将包含数字错误代码,您是否尝试过查找这些错误代码?在你的问题中发布一个异常示例,确保突出显示文本并单击
{}
按钮以使其格式良好。如果你真的想友好,最后一行应该是
抛出新异常(rs,e)
,这样链上的下一个人可以检查内部异常并查看堆栈跟踪等等。(也可以抛出一个自定义异常,而不是一个通用的
异常
),但实际上我需要区分它们,我需要根据数据库错误的类型抛出不同的异常。
        try
        {
            var numInserted = DbUtils.IgnoreErrors(_db, () => DbUtils.InsertEntity(_db, someEntity), DbUtils.IsDuplicateInsertError).Item1;
            // no FK exception, but maybe unique index violation, safe
            // to keep going with transaction
        }
        catch (DbUpdateException e)
        {
            if (DbUtils.IsForeignKeyError(e))
            {
              // you know what to do
            }
            throw; // rethrow other db errors
        }