C
C#β€’4w 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"]
};
}
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();
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?
2 Replies
Unknown User
Unknown Userβ€’4w ago
Message Not Public
Sign In & Join Server To View
malkav
malkavβ€’4w ago
Am I using both? oh dear.. hang on πŸ˜… That was the issue, thanks!