1

Is it possible to detect an error in a connection before we get an application "Transport-level error" using Linq?

Lets say that I have a SQL server called SQLServer1, and I am running an application that connects to that server using LinQ to get some information.

I decide to change the server Name to SQLServer2. The next time my application run I will get an error like this:

"A transport-level error has occurred when receiving results from the server. (provider: TCP Provider, error: 0 - The specified network name is no longer available.)"

Because LinQ doens't know that there was a change!

How can I catch this during runtime? Is it possible to extend the DataContext class to check somehow the connection before getting the data?

Thanks!

4

2 回答 2

2

这是我扩展课程的方式。我使用单例模式来调用数据上下文,这导致每个页面请求都会实例化一个数据上下文对象,而不管调用单例的次数如何。在每个请求第一次调用单例时,我运行 DataContext.DatabaseExists(),如果它为 false,我会优雅地处理错误。现在,每当我的任何代码尝试对数据上下文执行任何操作时,它都会向我的用户提示“抱歉,数据库已关闭”消息。

ASP.NET C# 代码:

namespace dal
{
    public partial class DataModelDataContext
    {
        public static DataModelDataContext DataContext
        {
              get
              {
                  if (System.Web.HttpContext.Current.Items["ModelDataContext"] == null)
                  {
                      DataModelDataContext datacontext = new DataModelDataContext();
                      //Once per page request, of the datacontext is requested, check to see if the database connection is valid.
                      if (!datacontext.DatabaseExists())
                      {
                           System.Web.HttpContext.Current.Response.Redirect("DatabaseIsDown.html");
                      }
                      System.Web.HttpContext.Current.Items["ModelDataContext"] = datacontext;

                  }
                  return (DataModelDataContext)System.Web.HttpContext.Current.Items["ModelDataContext"];
              }
        }
    }
}
于 2010-02-26T17:49:49.623 回答
0
try
{
   // run linq query here
}
catch (Exception e)
{
   // take appropriate action to handle the error like updating the connection string, etc.
}
于 2009-06-05T21:49:29.173 回答