SqlDependency.Start(connectionString) return every

2020-03-27 08:21发布

问题:

I set All right to acces the DataBase

use DbName
GRANT SUBSCRIBE QUERY NOTIFICATIONS TO dbuser
use DbName
GRANT SELECT ON OBJECT::schema.tableName TO dbuser
Use DbName
GRANT RECEIVE ON QueryNotificationErrorsQueue TO dbuser
ALTER DATABASE DbName SET TRUSTWORTHY ON
use DbName
alter database DbName SET ENABLE_BROKER

but when I start SqlDependency:

bool started = SqlDependency.Start(connectionString);

//started is false and then I get this error

An exception of type 'System.InvalidOperationException' occurred in System.Data.dll but was not handled in user code Additional information: When using SqlDependency without providing an options value, SqlDependency.Start() must be called prior to execution of a command added to the SqlDependency instance.

C# code:

private static bool notificationEnabled = false;
private string connString= "Data Source=(local);Initial Catalog=MyDB;UID=dbuser; PWD=pass;";
    public static void EnableNotifications()
    {
        // prevent for calling twice 
        if (notificationEnabled)return; 

        System.Web.Caching.SqlCacheDependencyAdmin.EnableNotifications(connString);
        //startResult is false always
        bool startResult = SqlDependency.Start(connString);
        notificationEnabled = true;
    }

回答1:

Try adding the queue name to your Start:

bool startResult = SqlDependency.Start(connString, queueName)

I also had to add the service name and timeout to my SqlDependency constructor to get things to work right. (its in VB, but you get the idea)

dependency = New SqlDependency(command, "Service=" + SERVICE_NAME + ";", Int32.MaxValue)


标签: c# asp.net tsql