gpt4 book ai didi

c# - 如何优雅地处理ASP.NET MVC 4中的数据库连接?

转载 作者:行者123 更新时间:2023-12-03 08:08:09 25 4
gpt4 key购买 nike

尝试连接到可能已关闭或在MVC 4中给出错误连接字符串的数据库时,如何正确处理错误?

我在Web.config中有我的字符串,并且它访问数据库的方式只是在每个 Controller 中实例化从DBContext派生的类,如下所示:
private DBEntities db = new DBEntities("database");
如果数据库已启动且一切都正确,则此方法工作正常,但如果不是,则我网站上的页面显示此错误:
Exception Details: System.ComponentModel.Win32Exception: The network path was not found
显然,我不希望出现这种情况,我想做的是有一种方法try catch错误并显示自定义错误页面(类似于404页面未找到)。

谢谢。

最佳答案

在函数中进行初始化

private DBEntities db;

// then in your function attempt to initialise
try{

db = new DBEntities("database");

db.Connection.Open();

}
catch(Exception ex){

if(db.Connection != ConnectionState.Closed){

db.Connection.Close();
db.Dispose();

//go to error page
}

}

关于c# - 如何优雅地处理ASP.NET MVC 4中的数据库连接?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13704830/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com