简体   繁体   中英

sqldependency not detecting change. What am I missing?

Im trying to check for any database changes using sqldependency and then send something to clients that are connected to signalr. The thing is, it seems that its not detecting changes. I feel theres something missing. heres the code:

[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);
    }
}

The problem is that SqlDependency requires resubscription. So, you should modify your OnDependencyChange method like this:

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);
}

Hope this helps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM