Search code examples
sqlsql-serverasp.net-core

ASP NET Core Microsoft.Data.SqlClient.SqlException (0x80131904)


I'm trying to make a selection from the database

Db db = new Db();
var con = await db.OpenConnection();

SqlCommand command = new SqlCommand("SELECT * FROM users", con);
SqlDataReader reader = await command.ExecuteReaderAsync();

while (await reader.ReadAsync())
{
    // ...
}

await db.CloseConnection(con);

But I get an exception

Microsoft.Data.SqlClient.SqlException (0x80131904): The object name 'users' is not valid.

I have no idea what's going on, because the database exists and the table exists too

enter image description here

Class code

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

namespace CarWashServer
{
    internal class Db
    {
        public async Task<SqlConnection> OpenConnection()
        {
            var con = new SqlConnection();
            con.ConnectionString = "Data Source=localhost;User ID=*****;Password=********;Connect Timeout=30;Encrypt=False;Trust Server Certificate=True;Application Intent=ReadWrite;Multi Subnet Failover=False";

            if (con.State != ConnectionState.Open)
                await con.OpenAsync();

            return con;
        }

        public async Task<int> CloseConnection(SqlConnection con)
        {
            await con.CloseAsync();
            return 0;
        }
    }
}

Solution

  • Ensure the table name in your database is actually "users". SQL Server table names are case-insensitive by default, but the name must match exactly, including any spaces or special characters.

    If the table is in a schema other than dbo, include the schema name:

    SELECT * FROM schema_name.users
    

    Use Square Brackets for Reserved Keywords:

    SELECT * FROM [users]