Reputation: 3923
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?
Upvotes: 0
Views: 9079
Reputation: 1789
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);
Upvotes: 1
Reputation: 10941
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();
}
Upvotes: 3