I'm creating a forum which is made up of topics, which are made up of messages.
When I try to implement the topic View in my Controller with:
public ActionResult Topic(int id) //Topic Id
{
using (var db = new DataContext())
{
var topic = db.Topics.Include("Messages").Include("Messages.CreatedBy").Include("CreatedBy").FirstOrDefault(x => x.Id == id);
//include the messages for each topic, and when they were created so that the last message can be displayed on the topic page
return topic != null ? View(topic) : View();
}
}
I get this error when I try to view the topic page:
ObjectDisposedException was unhandled by user code
The ObjectContext instance has been disposed and can no longer be used for operations that require a connection.
The error doesn't seem specific to a certain line, as when I remove the offending line, the same error apperars earlier on.
I have solved this by using:
DataContext db = new DataContext();
at the start of the controller and:
protected override void Dispose(bool disposing)
{
db.Dispose();
base.Dispose(disposing);
}
at the end (and taking using
out)
Although this works, I am curious as to why "Using" doesn't work, and I'm not really happy having the connection open throughout the controller, and disposing of it manually at the end.