try/catch
ブロックを使用してusing
を包みます。
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();
}
}
}
try/catchブロックで 'using 'をラップしてください。 –
@KishoreJangidありがとうございます。私はいくつかの他の方法があると思った:) –