处理Entity Framework 4中的异常。

7

我需要一种方法来区分使用实体框架LINQ的SQL异常,例如如何区分外键约束违规或唯一约束违规,当我从DbUpdateException中获得大量嵌套的内部异常和无用的长错误消息时?是否有更低级别的异常,我可以像"catch FKException"; catch "uniqueException"这样做。


内部异常通常包含数字错误代码,您是否尝试查找这些代码?在您的问题中发布一个异常示例,确保突出显示文本并单击“{ }”按钮以使其格式化得很好。 - Scott Chamberlain
3个回答

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

4
如果你想真的友好一些,最后一行应该是throw new Exception(rs, e),这样上面的人可以检查内部异常并查看堆栈跟踪等信息。(抛出自定义异常而不是通用的 Exception 也会更好)。 - Scott Chamberlain
但我实际上需要区分它们,我需要根据数据库错误的类型抛出不同的异常。 - Cristiano Coelho

5

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

0

我为此编写了几个实用方法:

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

以下是如何使用它的方法。插入一个可能重复的行的示例:

DbUtils.IgnoreErrors(_db, () => DbUtils.InsertEntity(_db, someEntity),
  DbUtils.IsDuplicateInsertError);

不会抛出任何异常。

与先前的示例类似,但明确处理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。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接