启动sql依赖项时无效的对象名称

时间:2014-09-01 10:02:55

标签: c# sql sql-server sql-server-2008-r2

这是我的代码

SqlDependency.Start(GetConnectionString(), getQuery());

其中getQuery()是:

private string getQuery() {
            return "SELECT firstName, lastName FROM dbo.Customer";
        }

我遇到了这个例外:

Invalid object name 'SELECT firstName, lastName FROM dbo.Customer'.

更新

    private string getQuery() {
        return "SELECT firstName, lastName FROM dbo.Customer";
    }

    public void Initialization()
    {
        // Create a dependency connection.
        SqlDependency.Start(GetConnectionString(), getQuery());
    }


    public void SomeMethod()
    {
        // Assume connection is an open SqlConnection.

        // Create a new SqlCommand object.
        using (SqlCommand command = new SqlCommand(
            getQuery(),
            new SqlConnection(GetConnectionString())))
        {
            // Create a dependency and associate it with the SqlCommand.
            SqlDependency dependency = new SqlDependency(command);
            // Maintain the refence in a class member.
            // Subscribe to the SqlDependency event.
            dependency.OnChange += new
               OnChangeEventHandler(OnDependencyChange);
            // Execute the command.
            using (SqlDataReader reader = command.ExecuteReader())
            {
                // Process the DataReader.
            }
        }
    }

然后从外面,我这样做:

printing p = new printing();
            p.Initialization();
            p.SomeMethod();

1 个答案:

答案 0 :(得分:2)

您正在使用SqlDependency.Start(string, string)重载,其中第二个字符串表示队列名称。 'SELECT firstName, lastName FROM dbo.Customer'不是有效的队列名称。

您需要为查询和inject that in the constructor创建一个SqlCommand:

var dependencyCommand = new SqlCommand();
dependencyCommand.CommandText = getQuery();

sqlDependency = new SqlDependency(dependencyCommand);
sqlDependency.Start(GetConnectionString());

至于你的编辑,你已经这样做了。只需删除SqlDependency.Start()的第二个参数。