Objectdisposedexception

Asked

Viewed 196 times

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 list meusObjetos outside the context of using I receive Exception with the following description:

Objectdisposedexception

The Objectcontext instance has been dropped and can no longer be used for operations requiring a connection.

I can even accept that for ObjectContext implement the interface IDisposable leaving the context of using his data is no longer accessible, but how then can I make my objects 'independent" of ObjectContext and remain existing even after the Dispose() thus maintaining the using?

  • 1

    The problem is that you are adding a reference to the data in objectContext and not making a copy of them.

  • exact, but there is some way to make a practical copy of them?

  • 1

    Cool that, huh? ) I find it unlikely to help but tried to play in a variable, even if it is just to test, and only then play in the list? Do the test by trying to access the variable outside the using. If you can, then try the list.

  • @bigown couldn’t quite understand what you meant...

1 answer

0

Apparently, the list was not materialized in the .ToList(), then we will have to be more assertive with the context to obtain a materialized list of fact:

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);
}
  • because it is great @Ciganomorrisonmendez o . Tolist() was to have materialized correct?

  • It depends, especially because this approach only materializes the list at the last possible moment.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.