sqldependency没有检测到变化。我错过了什么?

时间:2015-01-05 09:39:40

标签: c# sql .net signalr sqldependency

我试图使用sqldependency检查任何数据库更改,然后向连接到signalr的客户端发送内容。问题是,它似乎没有检测到变化。我觉得有些东西不见了。继承人代码:

[HubName("DataHub")]
public class DataHub : Hub
{
    public void pushOnChange() 
    {
        string connection = "data source=fourthD;initial catalog=dash;integrated security=True;multipleactiveresultsets=True;application name=EntityFramework"";
        SqlDependency.Start(connection);
        SqlConnection connectionString = new SqlConnection(connection);
        connectionString.Open();

        using (SqlCommand command=new SqlCommand("SELECT * FROM dbo.insight", connectionString))
        {
            command.Notification = null;
            SqlDependency dependency = new SqlDependency(command);
            dependency.OnChange += new OnChangeEventHandler(OnDependencyChange);
            command.ExecuteReader();
        }
    }


    void OnDependencyChange(object sender, SqlNotificationEventArgs e)
    {
        Dictionary<string, string> data = new Dictionary<string, string> { };
        data.Add("Id","34");
        data.Add("DeviceId", "163-117")
        data.Add("DeviceUserName", "Someone");

        var result = new[] { data };

        Clients.All.addData(result);
    }
}

1 个答案:

答案 0 :(得分:0)

问题是SqlDependency需要重新订阅。因此,您应该像这样修改OnDependencyChange方法:

void OnDependencyChange(object sender, SqlNotificationEventArgs e)
{
    // Resubscription
    using (SqlCommand command=new SqlCommand("SELECT * FROM dbo.insight"
            , connectionString))
    {
        command.Notification = null;
        SqlDependency dependency = new SqlDependency(command);
        dependency.OnChange += new OnChangeEventHandler(OnDependencyChange);
        command.ExecuteReader();
    }

    Dictionary<string, string> data = new Dictionary<string, string> { };
    data.Add("Id","34");
    data.Add("DeviceId", "163-117")
    data.Add("DeviceUserName", "Someone");

    var result = new[] { data };

    Clients.All.addData(result);
}

希望这有帮助。