Hanho
Hanho

Reputation: 229

C# Casting item from SqlConnection to expose available items

I have a SQL query which I'm calling directly in code using plain ADO.NET (not Entity Framework) due to the stored procedure containing a pivot table which can potentially return a variable number of columns depending on the parameter input.

I've got to the stage where I can get a list of row data from the query and while debugging, if I drill down deep enough on the base properties, I can see that the object contains the 2 properties that I need (_fieldNameLookup and _values).

I am trying to access these values but I am not sure how I'm meant to be casting the items to expose the properties that I need.

The C# query is as follows:

using (var conn = new SqlConnection(ConfigurationManager.ConnectionStrings["Services"].ToString()))
{
    conn.Open();
    var cmd = conn.CreateCommand();

    cmd.CommandText = "[SPROCQUERY]";
    cmd.CommandType = CommandType.StoredProcedure;
    var queryData = cmd.ExecuteReader();

    var crei = new List<Items>();

    while (queryData.Read())
    {
        for (int i = 0; i < queryData.FieldCount; i++)
        {
            var x = queryData[i]; <-- I am trying to expose values in this object
        }
    }

    queryData.Close();

    return null;
}

Using intellisense on var x shows up with generic properties such as Equals, GetType, ToString.

Thanks

Upvotes: 0

Views: 80

Answers (1)

Russ
Russ

Reputation: 4173

queryData is your DbDataReader. Referencing an index on the default property simply returns an object of the column number.

To find out the column name, use the GetName() method of queryData, and to get the type, use GetFieldType():

Type t = queryData.GetFieldType(i);

To reference properties of your object--you need to cast it to the appropriate type.

Upvotes: 2

Related Questions