This is my data access method which fetch data from Oracle database and binds it as XML response.
public IEnumerable<InquiryResponse> GetData(int storeNumber, List<RequestItem> requestItems)
{
var data = new List<InquiryResponse>();
using (var connection = new OracleConnection(connectionString))
{
connection.Open();
var batches = requestItems.Select((item, index) => new { item, index })
.GroupBy(x => x.index / 100)
.Select(group => group.Select(x => x.item).ToList())
.ToList();
Dictionary<int, bool> cLResponses = new Dictionary<int, bool>();
Parallel.ForEach(batches, batch =>
{
string commonList = string.Join(",", batch.Select(item => $"'{item.CommonLot}'"));
string query = Query goes here which will take commonList in IN operator and storeNumber
using (OracleCommand command = new OracleCommand(query, connection))
{
command.Parameters.Add("StoreNumber", OracleDbType.Int32).Value = storeNumber;
using (OracleDataReader reader = command.ExecuteReader())
{
while (reader.Read())
{
int currentNumber;
if (int.TryParse(reader["RequestNumber"].ToString(), out currentNumber))
{
//Data from db will be mapped in XML format for individual values
data.Add(InquiryResponse);
cLResponses[currentNumber] = true;
}
else
{
Console.WriteLine($"Invalid RequestNumber format in database result: {reader["RequestNumber"]}");
}
}
foreach (var b in batch)
{
int number;
if (int.TryParse(b.CommonLot.ToString(), out commonLot))
{
if (!cLResponses.ContainsKey(commonLot) || !cLResponses[commonLot])
{
foreach (var request in requestItems)
{
if (b.CommonLot == request.CommonLot)
{
var defaultResponse = CreateDefaultResponse(commonLot.ToString(), b.Sub.ToString());
data.Add(defaultResponse);
}
}
}
}
else
{
// Handle the case where parsing fails
throw new HttpException((int)HttpStatusCode.BadRequest, $"Invalid CommonLot format in request: {b.CommonLot}");
}
}
}
}
}
);
}
return data.OrderBy(item => item.InquiryItems.InquiryItem.Sub);
}
Getting object reference not set to an instance of an object when testing on Postman(i.e. instance deployed on server) but the code runs well on local.
Same method is working when using foreach in spite of parallel.foreach
foreach (var batch in batches) {
Can someone please help me what is wrong with the code when using parallel.foreach