【发布时间】:2017-11-23 18:22:20
【问题描述】:
使用 Linq to Sql 构建 C# MVC Web 应用程序以查询 SQL 数据库。 如果数据库应该脱机以避免黄屏死机,我正在尝试捕获异常。
经过调试,我发现了两件事。首先,DataContext的创建并没有检查sql server是否可用。其次,在 rows 变量中存储了一条错误消息(或异常!?)。
永远不会到达下面代码中的 Catch 语句。所以当我试图从视图中的模型读取数据时,我得到了黄屏死机。
为什么没有到达 Catch 语句?
代码:
try
{
//Creating DB Context
var con = ConfigurationManager.ConnectionStrings["teststring"].ConnectionString;
TestDataContext db = new TestDataContext(con);
//Querying database. This should cause an exception to be thrown!?
var rows = from s in db.Table
orderby s.Id descending
select s;
//Returning the View with the data
return View(rows);
}
catch (Exception ex)
{
ErrorInfo err = new ErrorInfo("Something went wrong when trying to query the database. See the log for details.");
err.WriteToErrorLog(ex);
return View("Error", err);
}
【问题讨论】:
-
由于延迟执行,对 db 的实际调用在视图中。你必须先实现它。添加
.ToList()并向视图发送列表。 -
谢谢@OfirWinegarten。这应该是公认的答案。
标签: c# model-view-controller linq-to-sql exception-handling