c# - EDIT: Why DataReader opened error occurs in this map? -


this question has answer here:

i'm trying pass map view. before populate data entities(session, movie, theater). start doing selection in sessions:

var sessions = s in db.sessions s.theaterid == id orderby s.movieid, s.time select s; 

this method. inside iterate on each session , verify if in map have list movie name key. when execution reaches thie point i'm receiving infamous "there open datareader associated command must closed first." exception. can't cast list because of types:

public actionresult myaction(int id)         {             theather theater = db.theater.find(id);             viewbag.theatername = theater.nomecinema;             var sessions = s in db.sessions s.theaterid == id orderby s.movieid, s.time select s;              var mapmovies = new dictionary<string, list<datetime>>();              foreach (session s in sessions)             {                 if ( !mapmovies.containskey( s.movie.moviename ) )                 {                     mapmovies.add( s.movie.moviename, new list<datetime>() );                 }                 mapmovies[s.movie.moviename].add(s.time);             }             viewbag.mapmovies = mapmovies;             return view();         } 

the error occurs in line:

if ( !mapmovies.containskey( s.movie.moviename ) ) 

what need pass error?

you using lazy load, when execute if ( !mapmovies.containskey( s.movie.moviename ) ) context tries issue query retrieve movie, in middle of enumeration (which holds datareader open) exception.

there 2 solutions:

1-materialize query converting result list:

var sessions = (from s in db.sessions      s.theaterid == id      orderby s.movieid, s.time      select s).tolist(); 

2-include movie entity on query eager load instead of lazy load:

var sessions = s in db.sessions.include(s => s.movie)     s.theaterid == id      orderby s.movieid, s.time      select s; 

Comments

Popular posts from this blog

php - Vagrant up error - Uncaught Reflection Exception: Class DOMDocument does not exist -

vue.js - Create hooks for automated testing -

Add new key value to json node in java -