Reputation: 6492
This could be a silly question. But I am new to EF.
I am using EF and I would like to retry connecting to database in case there is error while opening the connection.How to handle exception while trying to open connection using DbContext.
using (var db = myDbFactory.GetContext())
{
// implementation goes here
}
Upvotes: 1
Views: 2071
Reputation: 12884
Wrap your using
with an try/catch
block.
try{
using (var db = myDbFactory.GetContext())
{
// implementation goes here
}
}
catch(Exception ex){
//Retry
}
Sometime back, I have written this exception helper class to get DbException from EF.
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();
}
}
}
Upvotes: 2