Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Returning results from stored procedure as IEnumerable

i am not sure how to properly complete this - i have a stored proc and i want to return the results as an IEnumberable

  public IEnumerable GetGuids(int id)
    {
        SqlCommand _command = new SqlCommand("storedProc");
        _command.CommandType = CommandType.StoredProcedure;
        _command.Parameters.AddWithValue("@ItemID", id);

        return _command.ExecuteReader();
    }

when i run this i get: ExecuteReader: Connection property has not been initialized.

like image 729
Masriyah Avatar asked Jan 21 '26 16:01

Masriyah


2 Answers

Your SqlCommand does not have a corresponding connection. Either use:

_command.Connection = conn;

or create the SqlCommand by using conn.CreateCommand(...)

like image 86
D.R. Avatar answered Jan 24 '26 06:01

D.R.


Initialize the SqlCommand with the SqlConnection and be sure that the SqlConnection is open. After that ExecuteReader gives an SqlDataReader and you must read through the reader and read the values

SqlDataReader reader = _command.ExecuteReader();

while(reader.Read()
{
   // readvalue of reader["columname"] and insert into a list or yield return it.
}
like image 26
Martijn van Put Avatar answered Jan 24 '26 04:01

Martijn van Put