0

Entity Framework: Calling 'Read' when DataReader is closed

I am getting this problem intermittently when i pound my service with parallel asynchronous calls.

i understand that the reader is accessed when calling .ToList() on my defined EF query.

I would like to find out what is the best practice in constructing EF queries to avoid this, and similar problems.

My architecture is as follows:

My Entity Data Layer is a static class, with a static constructor, which instantiates my Entities (_myEntities). It also sets properties on my entities such as MergeOption.

This static class exposes public static methods which simply access the Entities.

public static GetSomeEntity(Criteria c) {
    ...
    var q = _myEntitites.SomeEntity.Where(predicate);
    return q.ToList();
}

This has been working in production for some time, but the error above and the one here happen intermittently, esp under heavy loads from clients.

I am also currently setting MultipleActiveResultSets=True in my connection string.

Community
  • 1
  • 1
Sonic Soul
  • 21,043
  • 31
  • 118
  • 190

2 Answers2

1

And that is the source of all your problems. Don't use shared context and don't use shared context as data cache or central data access object - it should be defined as one of the main rules in EF. It is also the reason why you need MARS (our discussion from previous question is solved now). When multiple clients executes queries on your shared context in the same time it opens multiple DataReaders on the same db connection.

I'm not sure why you get your current exception but I'm sure that you should redesign your data access approach. If you also modify data on shared context you must.

Community
  • 1
  • 1
Ladislav Mrnka
  • 349,807
  • 56
  • 643
  • 654
  • correct again! initially i was worried about overhead of creating a new object context reference, and setting all of its properties (tracking, timeout) but i just run some measured tests, and there isn't that much differe. thanks again! – Sonic Soul Feb 02 '11 at 19:34
0

The issue may come from the connection timeout when trying to get a huge amount of data from your database, so trying to set the connection timeout in your code as below:

Entity 5 ((IObjectContextAdapter)this.context).ObjectContext.CommandT‌​imeout = 1800;

Other Entity: this.context.Database.CommandTimeout = 1800;

Loc Huynh
  • 266
  • 3
  • 3