c# - 尝试 Catch EF6 尝试连接到 SQL Server

标签 c# entity-framework

我正在尝试在 EF 6 尝试连接到 SQL 服务器时执行 try catch,这样我不仅可以记录错误消息,还可以向用户发出明确的消息,指出“连接到时出错数据库。请联系您的系统管理员”。

这样做的原因是我不想向用户显示从 EF 收到的冗长的错误消息说明

"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."

下面是我的代码:

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)
        {


        }
    }
}

存储库中的代码如下:

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

这样做的另一个原因是这个 dbcontext 连接到一个 SQL 服务器,由于各种原因多次不可用(我知道修复 SQL 服务器会更好,但它不属于我们,第三方是不愿意修复它)

我也不想在上面提到的每个存储库方法周围放置一个 try catch block (这只是我上面提到的一个存储库代码,我们还有另外 20 个用于此 SQL 数据库服务器的不同存储库)

我已经在网上搜索了很多,但找不到任何相关信息,因此,如果有人能帮我解决这个问题,我将不胜感激。

最佳答案

DbContext 是 ObjectContext 的包装器,检查这个 How to: Manually Open the Connection from the Object Context在访问 repo 或创建代理类来实例化 repo 之前?

using (AdventureWorksEntities context =
    new AdventureWorksEntities())
{    
    context.Connection.Open();

或者检查数据库是否存在Database.Exists Method

简单地使用 Exists

if (myDbContext.Database.Exists()){
// call your operation here
}

关于c# - 尝试 Catch EF6 尝试连接到 SQL Server,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45346796/

相关文章:

c# - 从 ComboBox (DropDownList) Winforms 中删除项目

c# - 算法挑战 : merging date range

c# - 如何检测重叠的开始和结束日期时间(C#、ASP.NET、MVC)

c# - 一个数据库上的多个 DbContext 代码优先迁移

c# - EF 中的 CurrentDateTime()

c# - 可以在 C# 4.0 中创建多类型 lambda 函数的单一多类型集合吗?

c# - 将图像写入 SQL Server CE

sql - Entity Framework : How to select specific fields from a singular Navigation Property?

c# - 使用 Entity Framework 的代码优先在保存时抛出 DbUpdateException

c# - Linq 对查询中的子项进行排序