我第一次尝试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 Server位于本地计算机上。我通过Visual Studio(IIS Express)运行代码。
在数据库上启用服务代理:
ALTER DATABASE SET ENABLE_BROKER GO
要订阅查询通知,我们需要授予IIS服务帐户
的权限GRANT SUBSCRIBE QUERY NOTIFICATIONS TO “<serviceAccount>”
我猜测第二点不是必需的,因为它是本地的。但我尝试给它一些权限。不知道他们是否正确,因为我认为它不使用app pool。并且不需要本地环境的许可。如果我自己是用户并自己创建了模式。
我看到的其中一个问题是:
alter authorization on database::<dbName> to [sa];
我也同意了这个许可。
答案 0 :(得分:0)
我失踪了:
dependency.OnChange += new OnChangeEventHandler(OnChange);
新代码如下:
SqlDependency dependency = new SqlDependency(command);
dependency.OnChange += new OnChangeEventHandler(OnChange);
现在我可以解雇了
void OnChange(object sender, SqlNotificationEventArgs e)