C
C#6mo 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 User6mo ago
Message Not Public
Sign In & Join Server To View
malkav
malkavOP6mo ago
Am I using both? oh dear.. hang on 😅 That was the issue, thanks!
Want results from more Discord servers?
Add your server