Search code examples
entity-framework-6entity-framework-coredatareader

Entity Framework 6 or Core - Read query result with a "DataReader" like pattern


is there a way to get a LINQ query result on a EF DBContext as a 'Typed Data Reader', in sucha a way that when i am reading de IQueryable result (ex with a .ToList()) I don't put all the result in memory?

I am expecting something like this (or equivalent):

var personQueryResult=dbContext.People.Where(…).Select(…).AsDataReader();
foreach(person in personQueryResult){
   //Here I expect that person is typed of the People Dbset<T> type, ex. a Person type and i can do:

person.Name="...";
person.Surname="...";
//etc.
}

Solution

  • There is not an explicit method that ensure you that that the collection would be scrolled trough a DbDataReader.

    Knowing the inheritance hierarchy of the EF's base classes, every usage of a foreach on a DbSet<T>,IQueryable<T> or IEnumerable<T>, avoiding any direct method that will trigger a query deferred execution (ex. ToList()) will prevent to load all the records in memory so that at every "MoveNext()" of the enumerator will be used the "Read()" of the underlying DbDataReader.