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

.net c# database entity-framework

Question

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?

1
0
8/11/2013 7:09:53 PM

Accepted 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();
}
3
8/11/2013 7:16:18 PM

Popular Answer

You are using Lazy Loading, which uses your already disposed DbContext. You need to turn off Lazy Loading, or just use Eager Loading for specific condition:

class SomeClass
{
    public int ID {get;set;}
    public virtual IList<SupportTicketMessage> Messages { get; set; }
}

var entry = db.Set<SomeClass>().Include("Messages").Single(t => t.ID = 1);


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow