简体   繁体   English

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

[英]Invalid object name when starting the sql dependency

This is my code 这是我的代码

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

where getQuery() is: 其中getQuery()是:

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

I got this exception: 我有这个例外:

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

Update 更新资料

    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.
            }
        }
    }

and then from outside, I do this: 然后从外面,我这样做:

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

You're using the SqlDependency.Start(string, string) overload, where the second string indicates a queue name. 您正在使用SqlDependency.Start(string, string)重载,其中第二个字符串表示队列名称。 'SELECT firstName, lastName FROM dbo.Customer' is not a valid queue name. 'SELECT firstName, lastName FROM dbo.Customer'不是有效的队列名称。

You need to create a SqlCommand for the query and inject that in the constructor : 您需要为查询创建一个SqlCommand并将其注入到构造函数中

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

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

As for your edit, you already do that. 至于编辑,您已经完成了。 Just remove the second argument to SqlDependency.Start() . 只需删除SqlDependency.Start()的第二个参数即可。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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