c# - DataContext Accessed After Dispose -


i'm using asp.net 4.0.

i've got following code returns error of "cannot access disposed object. object name: 'datacontext accessed after dispose.'."

 public ienumerable<batchheader> getheaders()             {                 using(nsfchecksdatacontext context = datacontext)                 {                     ienumerable<batchheader> headers = (from h in context.batchheaders                                                         select h);                                     return headers;                                             }             } 

if change to:

public ienumerable<batchheader> getheaders()         {             using(nsfchecksdatacontext context = datacontext)             {                             return context.batchheaders.tolist();                                         }         } 

it work fine. i'm using method populate radgrid. can explain why second method work not first?

thanks.

the first doesn't work because when method returns data context instantiated in using block disposed. however, ienumerable<batchheader> returned lazily evaluated , needs data context alive enumerate results.

you this:

 public ienumerable<batchheader> getheaders() {      using(nsfchecksdatacontext context = datacontext) {                   foreach(var header in context.batchheaders) {              yield return header;          }      }  } 

the second block works because query results enumerated on , stored in memory before data context disposed of. after happens, data context isn't needed anymore. however, careful when using code second block; if batchheaders table large pulled memory.

now, , here serious part of answer: i absolutely can't stand seeing queries instantiate data contexts execute. want know , control when data contexts being used.


Comments

Popular posts from this blog

asp.net - repeatedly call AddImageUrl(url) to assemble pdf document -

java - Android recognize cell phone with keyboard or not? -

iphone - How would you achieve a LED Scrolling effect? -