Showing posts with label Data Reader. Show all posts
Showing posts with label Data Reader. Show all posts

Friday, May 21, 2021

How to: Looping through reader count dynamically C#

Here is how this can be done once you have the data call via Read methods
   
using (var reader = await sqlDbContext.ExecuteReaderAsync(command))
{
   
    while (await sqlDbContext.ReadAsync(reader))
    {
        // when count greaterthan 1
        if (reader.FieldCount > 1)
        {
            if (!string.IsNullOrEmpty(reader["ItemD"].ToString()))
            {
                mobilityChangeOrdersItem.ItemID= reader["ItemID"] == null ? 0 : Convert.ToInt32(reader["ItemID"].ToString());
            }
            if (!string.IsNullOrEmpty(reader["ID"].ToString()))
            {
                mobilityChangeOrdersItem.ID = reader["ID"] == null ? 0 : Convert.ToInt32(reader["ID"].ToString());
            }
        }
    }

    //Looping through complete list of return variables to find out requrired column
    string errorMessge = " SQL Message: -- *Start* ItemD -- :: " + mobilityChangeOrdersItem.ItemD;
    while (await reader.NextResultAsync())
    {
        var fieldvalues = Enumerable.Range(0, reader.FieldCount).Select(i => reader.GetName(i)).ToArray();

        while (await reader.ReadAsync())
        {
            if (fieldvalues.Contains("ErrorMessage"))
            { 
                errorMessge += Environment.NewLine + " ErrorMessage : " + reader["ErrorMessage"].ToString();
            }
            if (fieldvalues.Contains("ErrorProcedure"))
            {
                errorMessge += Environment.NewLine + " ErrorProcedure : " + reader["ErrorProcedure"].ToString();
            }
        }
        errorMessge += Environment.NewLine + " SQL Message: -- *End*";
        mobilityChangeOrdersItem.StatusMessage = errorMessge;
    } 
    mobilityChangeOrdersList.Add(mobilityChangeOrdersItem);
}

Hope this helps 😀

How to : Check if a column exists in a datareader in C#

 Here is how we can do in  C# supported Frameworks!!

var fieldvalues = Enumerable.Range(0, reader.FieldCount).Select(i => reader.GetName(i)).ToArray();

//get column name here
if (fieldvalues.Contains("ErrorMessage"))
{
    errorMessge += Environment.NewLine + " ErrorMessage : " + reader["ErrorMessage"].ToString();
}
//get column name here
if (fieldvalues.Contains("ErrorProcedure"))
{
    errorMessge += Environment.NewLine + " ErrorProcedure : " + reader["ErrorProcedure"].ToString();
}

BTW, ErrorMessage will return the value after checking these fields 

Hope this helps 😀