为什么"配置"工作中,而不是与QUOT;使用(VAR DB =新的DataContext())"? [英] Why does "Dispose" work, and not "using(var db = new DataContext())"?

查看:246
本文介绍了为什么"配置"工作中,而不是与QUOT;使用(VAR DB =新的DataContext())"?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创建它是由主题,这是由消息的论坛。

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是由用户code

ObjectDisposedException was unhandled by user code

的ObjectContext的实例已设置,不能再被用于需要连接的操作。

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

错误似乎并没有具体到一定行,因为当我删除有问题的线路,同样的错误apperars早些时候。

The error doesn't seem specific to a certain line, as when I remove the offending line, the same error apperars earlier on.

我以解决了这个:

DataContext db = new DataContext();

在控制器的开始和

at the start of the controller and:

protected override void Dispose(bool disposing)
{
    db.Dispose();             
    base.Dispose(disposing);
}

末(使用以 出)

虽然这个工作,我很好奇,为什么使用不工作,我不具有连接整个控制器打开,并在年底的手工处理它真的很高兴。

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.

推荐答案

不要你的任何实体启用延迟加载?好像有你的意见得到执行的查询,但你处理你的情况下被执行之前,他们(因此错误说它已经释放)。如果你把处置控制器Dispose方法,视图将得到控制之前执行和背景布置。

Do any of your entities have lazy loading enabled? It seems like there are queries getting executed in your views but you are disposing your context before they get executed (hence the error saying it is already disposed). If you put the disposal in the controller Dispose method, the view will get executed before the controller and context is disposed.

我建议安装Glimpse.Mvc5和Glimpse.EF6包。一旦配置一睹你可以看到每一个被你的网页执行查询。你可能会惊讶地看到一些额外的查询被执行,你不打算。这就是为什么我不建议直接在视图中使用的实体。

I recommend installing Glimpse.Mvc5 and Glimpse.EF6 packages. Once you configure glimpse you can see every query that gets executed in your page. You might be surprised to see a few additional queries get executed that you did not intend. This is why I don't recommend using entities directly in your views.

这篇关于为什么"配置"工作中,而不是与QUOT;使用(VAR DB =新的DataContext())"?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆