我有一些关于ASP.NET MVC应用程序中实体框架上下文的期望生命周期的问题。让上下文在尽可能短的时间内保持活跃不是最好的吗?
考虑以下控制器操作:
public ActionResult Index()
{
IEnumerable<MyTable> model;
using (var context = new MyEntities())
{
model = context.MyTable;
}
return View(model);
}
上面的代码将无法工作,因为在视图呈现页面时,实体框架上下文已超出范围。其他人会如何组织上面的代码?
发布于 2012-05-28 06:27:04
我同意每个请求有一个上下文,我们通常通过使用Ninject绑定上下文.InRequestScope来做到这一点,这真的很好用,它是:
Bind<MyContext>().ToSelf().InRequestScope();
此外,枚举尽可能接近查询的集合也是一种很好的做法,例如:
public ActionResult Index()
{
IEnumerable<MyTable> model;
using (var context = new MyEntities())
{
model = (from mt in context.MyTable
select mt).ToArray();
}
return View(model);
}
这将帮助您避免在视图中无意地增加查询。
发布于 2012-05-28 06:27:23
你能像这样使用LINQ的.ToList()
扩展方法吗:
public ActionResult Index()
{
IEnumerable<MyTable> model;
using (var context = new MyEntities())
{
model = (from mt in context.MyTable
select mt).ToList();
}
return View(model);
}
https://stackoverflow.com/questions/10777630
复制相似问题