C# – The ObjectContext instance has been disposed and can no longer be used for operations that require a connection. – List

cdatabaseentity-frameworknet

In my ASP.NET MVC4 project I got an entity that has a list of another entity.

public virtual IList<SupportTicketMessage> Messages { get; set; }

I can access the messages just fine however when I exit the dbcontext (exit using) I get the error:

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

I perfectly understand why I get the error but I'm wondering how I should deal with it? How can I access the messages when I'm not in the dbcontext anymore?

Best Answer

You should include them in your original query. You can do this using Include:

List<Item> items;
using (var context = new YourContext())
{
    items = context.Items.Include(x => x.Messages).ToList();
}
Related Topic