Yalda
Yalda

Reputation: 684

Using Linq, I get this: There is already an open DataReader associated with this Command which must be closed first

Here's what I'm trying to do:

IEnumerable<OfficeView> allOffices = GetAllOffices(); //this method also uses some linq query
foreach (var office in allOffices)
{
    officeSales.Add(
             new Tuple<int, decimal>(office.Id, GetSaleAmount(office.Id, someParams)));
}


public decimal GetAgentSaleAmount(int officeRef, someTypes someParams)
{
    var q = ObjectQuery.Where
                (i => i.officeId == officeRef && i.someOtherStuff == someParams)
                .ToList();

    return q.Sum(i => i.NetPrice);
}

I can't set MultipleActiveResultSets = true. Instead, as suggested here, I tried to do .ToList() before doing the summation, but got the same error. (and even if I wouldn't get the error, I think it would cause heavy load to fetch everything just to get the summation of one field)

I will be super thankful for any suggestion to solve this problem!

Update: The problem was all about GetAllOffices(), which returned IEnumerable (which leaves the DataReader open). I changed the first line as below and it worked. Thanks a lot guys :)

IEnumerable<OfficeView> allOffices = GetAllOffices().ToList();

Upvotes: 0

Views: 513

Answers (2)

Kosala W
Kosala W

Reputation: 2143

I think you are trying to do both adding and querying at the same time.You need to finish adding "Sale" object to "Sales" collection before trying to calculate the sales value.

In other words, you cannot query until the transaction is committed. Hope that helps.

Upvotes: 1

nikodz
nikodz

Reputation: 727

Error said that reader is already opened, that means that you have run some query before which needs to close. Write .ToList() to that linq query and do same for other queries too.

Upvotes: 2

Related Questions