MVC中没有处理对象上下文的最佳做法? [英] Best practises in MVC for not disposing the object context?

查看:88
本文介绍了MVC中没有处理对象上下文的最佳做法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个名为Student的Entity Framework类。它有一个类的列表。现在,每当我(从我的角度来看)参考ViewBag.Student.Classes,它会失败,一个对象处理异常,因为我的控制器如下所示:

  using(var myObjectContext = new ModelContainer()){
ViewBag.Student = myObjectContext.UserSet.OfType< Student>()。FirstOrDefault(s => s.Id == ActiveStudentSignedIn);
}

现在,我知道我也可以在viewbag中传入学生的课程但是,当使用依赖于学生及其细节的强类型部分视图时,会增加复杂性。



我认为没有使用关键字在那里,因为不会让垃圾收集者收集太多垃圾?



我显然做错了事情。但是什么?

解决方案

有两种方法可以解决这个问题:




  • 在查询中使用热切加载( Include 方法),并直接从控制器操作传递所需的所有数据。目前您收到异常,因为您的视图正在尝试触发延迟加载并对数据库执行另一个查询,但上下文已被处理。

  • 延长上下文的生命周期=不要为每个动作创建上下文。为每个控制器创建单个上下文(为每个请求创建新的实例),并在控制器的 Dispose 方法中配置上下文。您还可以从外部依赖注入将上下文注入到控制器中,但这需要一些其他基础设施。


I have an Entity Framework class called Student. It has a list of Classes. Now, everytime I (from my view) refer to ViewBag.Student.Classes, it fails with an object disposed exception, because my controller looks like this:

using(var myObjectContext = new ModelContainer()) {
    ViewBag.Student = myObjectContext.UserSet.OfType<Student>().FirstOrDefault(s => s.Id == ActiveStudentSignedIn);
}

Now, I know I could just pass in the student's classes in the viewbag too, but that would increase complexity when using strong-typed partial views that rely on a student and its details.

I think it would be wrong to not having the "using" keyword there, because wouldn't that leave up too much garbage for the garbage collector to collect?

I'm obviously doing something wrong. But what?

解决方案

There are two ways to solve this:

  • Use eager loading (Include method in query) and pass all data you need in view from your controller action directly. Currently you receive exception because your view is trying to trigger lazy loading and execute another queries to database but the context is already disposed.
  • Extend lifetime of your context = don't create context per action. Create single context per controller (new instance is created for every request) and dispose context in controller's Dispose method. You can also inject the context into controller from outside - dependency injection but that would require some other infrastructure.

这篇关于MVC中没有处理对象上下文的最佳做法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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