我第一次尝试SqlDepenedency。我不会收到任何关于数据库更新的通知。
我在里面放置断点:OnChange(object sender, SqlNotificationEventArgs e),
但它永远不会被击中。
这是我的代码:
protected void Page_Load(object sender, EventArgs e)
{
Label1.Text = "Cache Refresh: " + DateTime.Now.ToLongTimeString();
DateTime.Now.ToLongTimeString();
// Create a dependency connection to the database.
SqlDependency.Start(GetConnectionString());
using (SqlConnection connection = new SqlConnection(GetConnectionString()))
{
using (SqlCommand command = new SqlCommand(GetSQL(), connection))
{
SqlDependency dependency =
new SqlDependency(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.
connection.Open();
dgHomeRequests.DataSource = command.ExecuteReader();
dgHomeRequests.DataBind();
}
}
}
private string GetConnectionString()
{
// To avoid storing the connection string in your code,
// you can retrieve it from a configuration file.
//return "Data Source=(local);Integrated Security=true;" +"Initial Catalog=AdventureWorks;";
return ConfigurationManager.ConnectionStrings["TestData"].ConnectionString;
}
private string GetSQL()
{
return "Select [Address] From [UserAccount1]";
}
void OnChange(object sender, SqlNotificationEventArgs e)
{
// have breakpoint here:
SqlDependency dependency = sender as SqlDependency;
// Notices are only a one shot deal
// so remove the existing one so a new
// one can be added
dependency.OnChange -= OnChange;
// Fire the event
/* if (OnNewMessage != null)
{
OnNewMessage();
}*/
}我还在Global.asax文件中放置了一些代码:
public class Global : HttpApplication
{
void Application_Start(object sender, EventArgs e)
{
// Code that runs on application startup
RouteConfig.RegisterRoutes(RouteTable.Routes);
BundleConfig.RegisterBundles(BundleTable.Bundles);
SqlDependency.Start(ConfigurationManager.ConnectionStrings["TestData"].ConnectionString);
}
protected void Application_End()
{
// Shut down SignalR Dependencies
SqlDependency.Stop(ConfigurationManager.ConnectionStrings["TestData"].ConnectionString);
}
}SQL服务器位于本地计算机上。我正在通过Visual (IIS Express)运行代码。
我猜第二点是不需要的,因为它是本地的。但我试着给了它一些许可。不知道他们是否正确,因为我不认为它在使用应用程序pool.And不需要本地env的许可。如果我自己是用户并自己创建了模式。
我看到的一个问题是:
alter authorization on database::<dbName> to [sa];我也同意了。
发布于 2017-09-27 22:41:03
我错过了:dependency.OnChange += new OnChangeEventHandler(OnChange);新代码看起来像:
SqlDependency dependency = new SqlDependency(command);
dependency.OnChange += new OnChangeEventHandler(OnChange);现在我可以解雇void OnChange(object sender, SqlNotificationEventArgs e)了
https://stackoverflow.com/questions/46434652
复制相似问题