SQLDependency OnChangeEvent未触发

时间:2013-11-14 15:57:19

标签: c# ado.net sql-server-2012 sqldependency

我有以下代码对数据库View执行SqlCommand:

public IEnumerable<PickNote> GetData()
        {
            using (var connection = new SqlConnection(ConfigurationManager.ConnectionStrings["BTNInternalData_LiveEntities"].ConnectionString))
            {
                connection.Open();
                using (var command = new SqlCommand(@"SELECT [PICKINGROUTEID],[CUSTOMER],[SALESNAME]
           FROM [dbo].[PickScreenData] WHERE DATEADD(dd, 0, DATEDIFF(dd, 0, [ACTIVATIONDATETIME])) = DATEADD(dd, 0, DATEDIFF(dd, 0, GETDATE())) or [EXPEDITIONSTATUS] = 3", connection))
                {
                    // Make sure the command object does not already have
                    // a notification object associated with it.
                    command.Notification = null;

                    var dependency = new SqlDependency(command);
                    dependency.OnChange += new OnChangeEventHandler(dependency_OnChange);

                    if (connection.State == ConnectionState.Closed)
                        connection.Open();

                    using (var reader = command.ExecuteReader())
                    {
                        var data = reader.Cast<IDataRecord>();

                        return data.Select(x => new PickNote
                        {
                            pickingRouteId = x["PICKINGROUTEID"].ToString()
                        }).ToList();
                    }
                }
            }
        }

private void dependency_OnChange(object sender, SqlNotificationEventArgs e)
    {
        // do stuff
    }

但是,dependency_OnChange方法仅在我的应用程序开始时调用,并且无论我的视图中的数据是否发生更改,都不会再次调用Invalid方法。我调试了SqlNotificationEventArgs并且Info是SqlNotificationEventArgs.Info但是我不确定为什么命令查询运行正常

修改

我更改了查询,以便直接查询表格,但Invalid仍然说public IEnumerable<PickNote> GetData() { using (var connection = new SqlConnection(ConfigurationManager.ConnectionStrings["AXLive"].ConnectionString)) { connection.Open(); using (var command = new SqlCommand(@" SELECT PICKINGROUTEID, EXPEDITIONSTATUS FROM [dbo].[WMSPICKINGROUTE] WHERE (EXPEDITIONSTATUS <> 20) AND (DATEADD(dd, 0, DATEDIFF(dd, 0, [ACTIVATIONDATETIME])) = DATEADD(dd, 0, DATEDIFF(dd, 0, GETDATE())) OR [EXPEDITIONSTATUS] = 3)", connection)) { // Make sure the command object does not already have // a notification object associated with it. command.Notification = null; var dependency = new SqlDependency(command); dependency.OnChange += new OnChangeEventHandler(dependency_OnChange); if (connection.State == ConnectionState.Closed) connection.Open(); using (var reader = command.ExecuteReader()) { var data = reader.Cast<IDataRecord>(); return data.Select(x => new PickNote { pickingRouteId = x["PICKINGROUTEID"].ToString() }).ToList(); } } } } 。这是新代码:

WMSPICKINGROUTE

{{1}}是我的视图从之前获取数据的表。

1 个答案:

答案 0 :(得分:1)

根据此MSDN page,您不能对引用视图的select语句使用SqlDependency。这似乎是个问题。重写你的查询以命中表,它应该可以工作。