Monday 21 September 2015

[Solved] : There is already an open DataReader associated with this Command which must be closed first.

The exception "There is already an open DataReader associated with this Command which must be closed first." occurs when you try to perform another read while there is an ongoing read. Most commonly when you are iterating through one result set and within the loop the you are trying to fetch another data set.

Following is a typical example for this.
 
             var res = GetPayrollforReport(month, year);            

            foreach (var payRoll in res)
            {
                PayrollViewModel pay = new PayrollViewModel();
                pay.PayRollId = payRoll.PayRollId;
                var emp = db.Employees.FirstOrDefault(e => e.EmployeeId == payRoll.EmployeeId);
            }

In here, its trying to fetch employee details inside the payroll loop. So this is leading to above exception. There are two solutions for this.
1. Caste the first fetch in to a proper list type.
 
             var res = GetPayrollforReport(month, year).ToList<PayRoll>();            

            foreach (var payRoll in res)
            {
                PayrollViewModel pay = new PayrollViewModel();
                pay.PayRollId = payRoll.PayRollId;
                var emp = db.Employees.FirstOrDefault(e => e.EmployeeId == payRoll.EmployeeId);
            }

2. Allowing MARS in your connection string. This can be easily fix by introducing the MultipleActiveResultSets=true param into your connection string.

No comments:

Post a Comment