C#C
C#2y ago
malkav

✅ Mapping IDataReader into typed class

I'm trying to get data from IDataReader into a typed model object. What I'm trying in my model is the following method:
public static TestDataObject Create(IDataRecord record)
{
    return new TestDataObject
    {
        Id = (Guid)record["id"],
        Name = (string)record["name"],
        Value = (string)record["value"]
    };
}

and at my API class where I'm trying to fetch data from the ADX cluster, I'm calling the following method:
private static IEnumerable<T> BuildResult<T>(IDataReader response, Func<IDataRecord, T> buildObject)
{
    Console.WriteLine("Building result");
    try
    {
        while (response.Read())
        {
            Console.WriteLine($"Working on nth response {response.NextResult()}");

            yield return buildObject(response);
        }
    }
    finally
    {
        response.Dispose();
    }
}

// Calling it like this:
TestDataObject[] result = BuildResult(response, TestDataObject.Create).ToArray();


However I keep getting Index was outside the bounds of the array as error

Which index? the ["id"] ones? what am I missing?
Was this page helpful?