TheEdge
TheEdge

Reputation: 9851

Open DataReader which must be closed first

I get the above error (subject line) when I deploy to the production server and iterate over locations in the foreach. To get it to work on the production server I had to convert to an array viz var locationArray = locations.ToArray(); and iterate locationArray.

So my question is when in TEST (running local while debugging in VS2013) I am running against a SQLExpress instance and in PRODUCTION I am running against a fully fledged SQLServer. However why does iterating locations not produce an error in TEST but does do so in PRODUCTION?

public IQueryable<State> StatesInCountryGet(long aCountryId)
{
    List<State> result = new List<State>();

    using (DataRepository dataRepository = DataRepository.Instance())
    {
        //#TODO: Find a better way to do a GROUP BY
        IQueryable<LocationsMapping> locations = dataRepository.Query<LocationsMapping>(r => r.CountryId == aCountryId);

        var locationArray = locations.ToArray();  //Why do I need to do this?
        foreach (LocationsMapping locationMapping in locationArray)
        {
            //Add the state if we don't have it already
            if (!result.Exists(r => r.Id == locationMapping.StateId))
            {
                result.Add(locationMapping.State);
            }
        }
    }
    return result.AsQueryable();
}

Upvotes: 0

Views: 102

Answers (1)

Marc Gravell
Marc Gravell

Reputation: 1062484

Different database editions have different features, and tools like ORMs often tailor their code to the specific platform to exploit feature differences. As such it is a really bad idea to test on a very different version. I strongly suggest you develop against developer edition.

Calling ToArray() forces the iteration to be fully evaluated (to the end of the sequence) immediately. This is actually a pretty common thing to do to avoid concurrent readers on one connection.

As for why: perhaps you have Multiple Active Result Sets (MARS) enabled on one but not the other; or perhaps it knows that MARS is never available on express, so doesn't try it - but it thinks that MARS might be available on full SQL Server, so tries to use it.

Upvotes: 2

Related Questions