缓存未在sqldependency中刷新

时间:2014-03-05 09:15:11

标签: c# asp.net .net sqldependency

我想在更改数据库时自动刷新数据。

我使用this documentation

并将页面加载的代码设为:

 protected void Page_Load(object sender, EventArgs e)
    {
        conString = "Data Source=MITEJ5-PC\\MITEJTECHONOLY;Initial Catalog=SSISTestDatabase;Integrated Security=SSPI;";

        SqlDependency.Start(conString);
        using (SqlConnection connection =
       new SqlConnection(conString))
        {
            using (SqlCommand command =
                new SqlCommand(GetSQL(), connection))
            {
                SqlCacheDependency dependency =
                    new SqlCacheDependency(command);
                // Refresh the cache after the number of minutes 
                // listed below if a change does not occur. 
                // This value could be stored in a configuration file. 
                int numberOfMinutes = 1;
                DateTime expires =
                    DateTime.Now.AddMinutes(numberOfMinutes);

                Response.Cache.SetExpires(expires);
                Response.Cache.SetCacheability(HttpCacheability.Public);
                Response.Cache.SetValidUntilExpires(true);

                Response.AddCacheDependency(dependency);

                connection.Open();

                gv.DataSource = command.ExecuteReader();
                gv.DataBind();
            }
        }
    }

 private string GetSQL()
    {
        return "select Name,Age,Address from tlbStudent;";
    }

但是当我运行它并在SQL表数据中进行更改时,它不会自动在网格上反映它。

上面的代码在哪里可以出错?

请帮帮我。

2 个答案:

答案 0 :(得分:2)

首先,您需要了解SqlDependency的工作原理。阅读The Mysterious Notification进行简短介绍。一旦您了解到工作中的真实功能是查询通知,您就可以了解使用通知的查询的限制,请参阅Creating a Query for Notification。一旦有这样的限制:

  

必须明确说明SELECT语句中的预计列,并且表名必须使用两部分名称进行限定。请注意,这意味着语句中引用的所有表必须位于同一数据库中。

对于未来的问题,请阅读Troubleshooting Query Notifications

答案 1 :(得分:0)

中的问题
private string GetSQL()
{
    return "select Name,Age,Address from tlbStudent;";
}

表名应为2部分“”

private string GetSQL()
{
    return "select Name,Age,Address from dbo.tlbStudent;";
}

根据文件

  

必须明确声明SELECT语句中的预计列,并且必须使用两部分名称限定表名。请注意,这意味着语句中引用的所有表必须位于同一数据库中。