C#Entityframework如何在打开DbContext时出错时处理异常

时间:2016-09-13 08:40:23

标签: entity-framework c#-4.0

这可能是一个愚蠢的问题。但我是EF的新手。

我正在使用EF,我想在打开连接时出现错误时重试连接到数据库。如何在尝试使用DbContext打开连接时处理异常。

using (var db = myDbFactory.GetContext())
{
// implementation goes here
}

1 个答案:

答案 0 :(得分:2)

using阻止你的try/catch

try{
    using (var db = myDbFactory.GetContext())
    {
        // implementation goes here
    }
}
catch(Exception ex){
    //Retry
}

不久之后,我编写了这个异常助手类来从EF获取DbException。

using System;
using System.Collections.Generic;
using System.ComponentModel.Composition;
using System.Data.Entity.Validation;
using System.Data.SqlClient;
using System.Linq;
using System.Text;

namespace JIMS.Common.Utils
{
    public static class ExceptionExtensions
    {
        public static IEnumerable<Exception> GetAllExceptions(this Exception ex)
        {
            Exception currentEx = ex;
            yield return currentEx;
            while ( currentEx.InnerException != null )
            {
                currentEx = currentEx.InnerException;
                yield return currentEx;
            }
        }

        public static IEnumerable<string> GetAllExceptionsAsString(this Exception ex)
        {
            Exception currentEx = ex;
            yield return currentEx.ToString();
            while ( currentEx.InnerException != null )
            {
                currentEx = currentEx.InnerException;
                yield return currentEx.ToString();
            }
        }

        public static IEnumerable<string> GetAllExceptionMessages(this Exception ex)
        {
            Exception currentEx = ex;
            yield return currentEx.Message;
            while ( currentEx.InnerException != null )
            {
                currentEx = currentEx.InnerException;
                yield return currentEx.Message;
            }
        }

        /// <summary>
        /// Tries to get Database Exception, if there is any SqlException in the exception hierarchy, else return the exception message.
        /// </summary>
        /// <param name="ex"></param>
        /// <returns>Exception Message</returns>
        public static string TryGetDbExceptionMessage(this Exception ex)
        {
            if ( ex.GetBaseException() is SqlException )
            {
                SqlException sqlex = (SqlException)ex.GetBaseException();
                return sqlex.Message;
            }
            if ( ex.GetBaseException() is DbEntityValidationException )
            {
                DbEntityValidationException dbEntityValidationException =
                    (DbEntityValidationException)ex.GetBaseException();
                StringBuilder sb= new StringBuilder();
                foreach ( var error in dbEntityValidationException.EntityValidationErrors.SelectMany(validationErrors => validationErrors.ValidationErrors) )
                {
                    sb.AppendLine(string.Format("Property Name: {0} \nError Message: {1}\n" ,error.PropertyName ,
                                                error.ErrorMessage));
                }
                return sb.ToString();
            }
            return ex.ToString();
        }                
    }
}