Reputation: 23
I have a little problem with my code.
I try to retrieve data from local SQL Server. The connection is right, and so is the stored procedure. But when I read rows from the SqlDataReader
, it is empty. But when I watch the SqlDataReader
, there is something with ? inside, but is not the result.
The SQL query works fine in SQL Server Management Studio.
Here is my code:
List<Customer> customers = new List<Customer>();
using (SqlConnection conn = new SqlConnection())
{
conn.ConnectionString = "Server=DESKTOP-U8E1S5I;Database=Queue;Trusted_Connection=true";
conn.Open();
SqlCommand command = new SqlCommand("GetCustomers", conn);
using (SqlDataReader reader = command.ExecuteReader())
{
while (reader.Read())
{
customers.Add(new Customer
{
Name = (string)reader["CustomerName"],
WaitingNumber = (int?)reader["CustomerNumber"],
EnterTime = (DateTime?)reader["CustomerNumber"],
Status = (int)reader["CustomerStatus"]
});
}
}
}
and the result is "Enumeration Yielded No Results" with two rows that contains ?: (break point is before the reader.read())
Enumeration Yielded No Results
Thank for help.
Upvotes: 1
Views: 799
Reputation: 38618
By default, the SqlCommand
has the property CommandType
defined as CommandType.Text
which is used by ad-hoc sql
. You have to specify you are using stored procedure
by setting CommandType
on your command. For sample:
SqlCommand command = new SqlCommand("GetCustomers", conn);
command.CommandType = CommandType.StoredProcedure;
Do not forget to add the namespace System.Data
.
Upvotes: 1
Reputation: 1883
You need to specify that you're using a stored procedure, see below
SqlCommand command = new SqlCommand("GetCustomers", conn);
command.CommandType = CommandType.StoredProcedure;
Or
SqlCommand command = new SqlCommand("GetCustomers", conn) {
CommandType = CommandType.StoredProcedure
};
Upvotes: 0