简体   繁体   中英

Invalid object name when starting the sql dependency

This is my code

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

where getQuery() is:

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. 'SELECT firstName, lastName FROM dbo.Customer' is not a valid queue name.

You need to create a SqlCommand for the query and inject that in the constructor :

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() .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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