为什么在更改数据库表中的单元格值时未触发OnChange事件?

时间:2018-07-28 06:10:14

标签: c# .net sql-server console-application sqldependency

过去24个小时,我一直在处理此代码,但是它无法正常工作。

我希望击中 OnChange 事件,如果我修改 Services 表中的单元格,但是无论如何我都不会这样做。

我已经在数据库上启用了服务代理,但是仍然无法使用。

代码:

class Program
    {
        static void Main(string[] args)
        {
            var cs = Utility.getConnectionString();
            using (SqlConnection connection = new SqlConnection(cs))
            {
                connection.Open();
                SqlCommand command = new SqlCommand(@"Select [Services].[ServiceName], [Services].[ServicePrice] from dbo.Services", connection);
                SqlDependency dependency = new SqlDependency(command);
                dependency.OnChange += new OnChangeEventHandler(OnChange);
                SqlDependency.Start(cs);
                command.ExecuteReader().Dispose();
            }
            Console.ReadKey();
        }

        private static void OnChange(object sender, SqlNotificationEventArgs e)
        {
            Console.WriteLine(e.Info);
        }
    }

使用“编辑更多”或“更新查询”对数据库进行更改。

enter image description here

3 个答案:

答案 0 :(得分:1)

以下是基于您的代码的有效示例,该事件在事件触发时显示SqlNotificationEventArgs值,并且仅在有效时重新订阅。

using System;
using System.Data;
using System.Data.SqlClient;

class Program
{

    static void Main(string[] args)
    {

        SqlDependency.Start(Utility.getConnectionString());

        GetDataWithSqlDependency();
        Console.WriteLine("Waiting for data changes");
        Console.WriteLine("Press any key to quit");
        Console.ReadKey();

        SqlDependency.Stop(Utility.getConnectionString());

    }

    static void GetDataWithSqlDependency()
    {

        using (var connection = new SqlConnection(Utility.getConnectionString()))
        using (var cmd = new SqlCommand(@"SELECT [Services].[ServiceName], [Services].[ServicePrice] from dbo.Services;", connection))
        {
            var dependency = new SqlDependency(cmd);
            dependency.OnChange += new OnChangeEventHandler(OnDependencyChange);
            connection.Open();
            cmd.ExecuteReader().Dispose();
        }

    }
    static void OnDependencyChange(object sender, SqlNotificationEventArgs e)
    {

        Console.WriteLine($"OnDependencyChange Event fired. SqlNotificationEventArgs: Info={e.Info}, Source={e.Source}, Type={e.Type}");

        if ((e.Info != SqlNotificationInfo.Invalid)
            && (e.Type != SqlNotificationType.Subscribe))
        {
            SqlDependency.Start(Utility.getConnectionString());
            GetDataWithSqlDependency();
            Console.WriteLine($"Data changed.");
        }
        else
        {
            Console.WriteLine("SqlDependency not restarted");
        }

    }

}

static class Utility
{
    public static string getConnectionString()
    {
        return @"Data Source=.;Initial Catalog=YourDatabase;Application Name=SqlDependencyExample;Integrated Security=SSPI";
    }

}

这是测试数据库的DDL:

CREATE DATABASE YourDatabase;
GO
ALTER DATABASE YourDatabase SET ENABLE_BROKER;
GO
USE YourDatabase;
GO
CREATE TABLE dbo.Services(
      ServiceName varchar(100) NOT NULL 
        CONSTRAINT PK_Services PRIMARY KEY
    , ServicePrice decimal(10,2) NOT NULL
);
GO

这些查询会触发OnChanged事件:

INSERT INTO dbo.Services VALUES('SomeService', 1.00);
GO
UPDATE dbo.Services SET ServicePrice = 2.00 WHERE ServiceName = 'SomeService';
GO
DELETE FROM dbo.Services WHERE ServiceName = 'SomeService';
GO

编辑:

如果您使用最低特权帐户运行应用程序(最佳做法),则下面是一个示例脚本,用于授予SqlDependency所需的最低权限。

--create user for schema ownership
CREATE USER SqlDependencySchemaOwner WITHOUT LOGIN;
GO
--create schema for SqlDependency objects
CREATE SCHEMA SqlDependency AUTHORIZATION SqlDependencySchemaOwner;
GO

--add existing login as a minimally privileged database user with default schema SqlDependency
CREATE USER YourLogin WITH DEFAULT_SCHEMA = SqlDependency;

--grant user control permissions on SqlDependency schema
GRANT CONTROL ON SCHEMA::SqlDependency TO YourLogin;

--grant user impersonate permissions on SqlDependency schema owner
GRANT IMPERSONATE ON USER::SqlDependencySchemaOwner TO YourLogin;
GO

--grant database permissions needed to create and use SqlDependency objects
GRANT CREATE PROCEDURE TO YourLogin;
GRANT CREATE QUEUE TO YourLogin;
GRANT CREATE SERVICE TO YourLogin;
GRANT REFERENCES ON
    CONTRACT::[http://schemas.microsoft.com/SQL/Notifications/PostQueryNotification] TO YourLogin;
GRANT VIEW DEFINITION TO YourLogin;
GRANT SELECT to YourLogin;
GRANT SUBSCRIBE QUERY NOTIFICATIONS TO YourLogin;
GRANT RECEIVE ON QueryNotificationErrorsQueue TO YourLogin;
GO

--grant permissions on user objects used by application
GRANT SELECT ON dbo.Services TO YourLogin;
GO

答案 1 :(得分:0)

完成。

这仅仅是因为我没有使用 sa 作为登录名。只有我将数据库更改为 sa ,并在连接字符串中使用了该数据库。奏效了。

讨论:

问题

它可能来自被映射到有时无效的Windows帐户的dbo。 “ dbo”实际上是创建数据库的用户。例如,如果我在工作时在便携式计算机上的SQL实例上创建示例,那么就会出现此问题,然后我回家然后继续在家。在家里,我无法访问域ActiveDirectory,并且示例突然停止工作,因为“ dbo”确实是我的Windows帐户,并且不再可用。 “ dbo”发送的消息(例如通知)位于sys.transmissions_queue中,状态为“无法从域控制器检索有关用户'...'的信息”。在数据库中运行EXECUTE AS USER ='dbo'也会显示相同的错误发生。在这种情况下,解决方法是将“ dbo”更改为有效的登录名,例如通过在DATABASE :: [dbname]上运行ALTER AUTHORIZATION到[sa];

答案 2 :(得分:-2)

  using (SqlConnection conn = new SqlConnection(connectionString))
        {
            conn.Open();

            SqlDependency.Start(connectionString);

            string commandText = "select ID, status from dbo.VendorSetup";

            SqlCommand cmd = new SqlCommand(commandText, conn);

            SqlDependency dependency = new SqlDependency(cmd);

            dependency.OnChange += new OnChangeEventHandler(dbChangeNotification);

            var reader = cmd.ExecuteReader();

            while (reader.Read())
            {
                var employee = new VendorSetup
                {
                    ID = Convert.ToInt32(reader["ID"]),
                    status = reader["status"].ToString(),
                    //Age = Convert.ToInt32(reader["Age"])
                };

                employees.Add(employee);
            }
        }

        return employees;
    }

    private void dbChangeNotification(object sender, SqlNotificationEventArgs e)
    {
        _hubcontext.Clients.All.SendAsync("displayNotification");
    }