ObjectDisposedException

2

I have the following code snippet:

var nivel = 1;
List<meuObjeto> meusObjetos = new List<meuObjeto>();

using(var objectContext = ((IObjectContextAdapter)db).ObjectContext)
{
   var cmd = string.Format(@"SELECT *
                             FROM meuObjeto
                             WHERE meuObjetoNivel = {0}", nivel);

   meusObjetos.AddRange(objectContext.ExecuteStoreQuery<meuObjeto>(cmd).ToList());
}

The problem is that when trying to access any object from the meusObjetos list outside the context of using I get the exception with the following description:

  

ObjectDisposedException

     

The ObjectContext instance has been dropped and can no longer be used   for operations that require a connection.

I can even accept that ObjectContext implement the IDisposable interface when exiting the context of using its data is no longer accessible, but how then can I make my objects "independent" from ObjectContext and remain in existence even after Dispose() of it, thus keeping using ?

    
asked by anonymous 26.01.2016 / 19:35

1 answer

0

Apparently, the list was not materialized in .ToList() , so we'll have to be more assertive with the context to get a materialized fact list:

using(var objectContext = ((IObjectContextAdapter)db).ObjectContext)
{
   var cmd = string.Format(@"SELECT *
                             FROM meuObjeto
                             WHERE meuObjetoNivel = {0}", nivel);

   var objetosMaterializados = objectContext.ExecuteStoreQuery<meuObjeto>(cmd).ToList();
   meusObjetos.AddRange(objetosMaterializados);
}
    
26.01.2016 / 20:04