I am trying to do a try catch in EF 6 when it tries to connect to the SQL server so that I can not only log the error message but also give a clear message to the user stating "There was an error connecting to the database. Please contact your system administrator".
The reason for this is I dont want to show the user the long winded error message received from EF stating
"An error occurred accessing the database. This usually means that the connection to the database failed. Check that the connection string is correct and that the appropriate DbContext constructor is being used to specify it or find it in the application's config file. See http://go.microsoft.com/fwlink/?LinkId=386386 for information on DbContext and connections. See the inner exception for details of the failure."
Below is the code that I have:
namespace MyRepositories.MSSQL.DatabaseContext
{
public class MyDbContext : DbContext
{
public MyDbContext()
: base("name=MyConnection")
{
}
public virtual IDbSet<DBConnection> DBConnections { get; set; }
public virtual IDbSet<CustomerAction> CustomerActions { get; set; }
public virtual DbSet<Action> Actions { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
}
}
}
And the code in repository is as below:
namespace myRepositories.MSSQL
{
public class AccRepository : BaseRepository, IAccRepository
{
public AccountsRepository(MyDbContext dbContext)
{
_databaseContext = dbContext;
}
public IQueryable<Role> GetRoles()
{
var roles = _databaseContext.Roles.AsQueryable();
return roles;
}
public IQueryable<UserRole> GetUserRoles()
{
var userRoles = _databaseContext.UserRoles.AsQueryable();
return userRoles;
}
public List<RolePermission> GetRolePermissions(Role role)
{
var rolePermissions = _databaseContext.RolePermissions.Where(s => s.RoleID == role.RoleID).ToList();
return rolePermissions;
}
public List<UserRole> GetUserRoles(UUser user)
{
var userRoles = _databaseContext.UserRoles.Where(s => s.UserID == user.UserID);
return userRoles.ToList();
}
}
}
The other reason for doing this is that this dbcontext connects to a SQL server which many times is unavailable for various reasons (I know it would be better to fix the SQL server, but it is not owned by us and third party are reluctant on fixing it)
Also I do not want to go and put a try catch block around each of the repository methods mentioned above (this is just one repo code I have stated above and we have another 20 different repositories for this SQL database server)
I have searched the web quite a lot now and unable to find anything around this and therefore would be very grateful if anyone out there could help me solve this issue.