我正在创建一个由主题组成的论坛,这些主题由消息组成.
当我尝试在我的控制器中实现主题视图时:
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();
}
}
Run Code Online (Sandbox Code Playgroud)
我尝试查看主题页面时收到此错误:
ObjectDisposedException未被用户代码处理
ObjectContext实例已被释放,不能再用于需要连接的操作.
该错误似乎并不特定于某一行,因为当我删除有问题的行时,早先出现相同的错误.
我用以下方法解决了这个问题:
DataContext db = new DataContext();
Run Code Online (Sandbox Code Playgroud)
在控制器的开头和:
protected override void Dispose(bool disposing)
{
db.Dispose();
base.Dispose(disposing);
}
Run Code Online (Sandbox Code Playgroud)
最后(并using取出) …