0

我在将 SqlDependency 服务与我的 Windows 窗体应用程序集成时遇到了一些问题,我希望有人可以帮助新手。我只想以此作为开头,我知道我的数据库连接字符串和我的查询语句是正确的。此外,我知道我的数据库上启用了服务代理。发行:

SELECT is_broker_enabled FROM sys.databases WHERE name = 'Database'

从查询中返回 1。

我在我的主要表单加载事件中启动依赖项,如下所示:

SqlDependency::Stop(Get_DB_String());
SqlDependency::Start(Get_DB_String());

然后我从我的数据库中提取如下:

    bindingSource->DataSource = GetData("Select * From Table", 
                                              Get_DB_String(), 
                                                 dataAdapter);
    dataGridView->DataSource = bindingSource;

其中 GetData 定义为:

DataTable^ GetData( String^ sqlCommand, String^ connectionString, SqlDataAdapter^ adapter )
   {
      SqlConnection^ Connection = gcnew SqlConnection(connectionString);
      SqlCommand^ command = gcnew SqlCommand(sqlCommand,Connection);
      command->Notification = nullptr;              
      SqlDependency^ dependency = gcnew SqlDependency(command);     
      dependency->OnChange += gcnew OnChangeEventHandler(this, &LabSchedule::Form1::OnChange);
      adapter->SelectCommand = command;
      DataTable^ table = gcnew DataTable;
      adapter->Fill(table);  
      return table;
   }

我的更改处理程序定义如下:

System::Void OnChange(System::Object^ sender, SqlNotificationEventArgs^ e)
{

    ISynchronizeInvoke^ i = (ISynchronizeInvoke^)this;

    if (i->InvokeRequired)
    {

        OnChangeEventHandler^ tempDelegate =
            gcnew OnChangeEventHandler(this, &LabSchedule::Form1::OnChange);

        array<System::Object^>^ args = { sender, e };

        i->BeginInvoke(tempDelegate, args);

        return;
    }

    SqlDependency^ dependency = (SqlDependency^)sender;
    dependency->OnChange -= gcnew OnChangeEventHandler(this, &LabSchedule::Form1::OnChange);

    if(dependency->HasChanges)
    {
        // This is where I check the properties of the notification  
        MessageBox::Show(e->Info.ToString() + "\n" + e->Source.ToString() + "\n" + e->Type.ToString());
    }

}

当我从本地客户端更改数据库中的某些内容时,它会触发更改事件,一切看起来都很好。但是,当我从另一台机器上的客户端启动更改时,永远不会触发 OnChange 事件。我假设我在做一些古怪的事情,但我没有洞察力来解决它。谢谢。

4

1 回答 1

0

经过看似无休止的研究,我遇到的问题根源于我的表格设计,而不是我的代码。以下是我可能为了解决问题而改变的三件事:

该语句不得引用大对象类型:text、ntext 和 image。

我使用“ntext”作为我的一列的数据类型。

该语句不能使用星号 ( *) 或 table_name.*语法来指定列。

最初,我使用通配符从表中选择数据。

SELECT 语句中的投影列必须明确声明,并且表名必须用两部分名称限定。

我没有在 SELECT 语句中使用由两部分组成的表名,即“Table_name”而不是“dbo.Table_name”。

这是一个很难确定的问题,我希望这可以帮助其他遇到类似问题的人。我在对问题的最初描述中说错了,因为我的查询虽然完全合法,但对 SqlNotifications 无效。

于 2012-02-13T14:48:09.713 回答