绕过“Dispose 之后访问 DataContext” ASP.NET MVC 视图中的错误
我有一个 ASP.NET MVC 2 操作,如下所示:
public ActionResult Index()
{
using(var db = new MyDataContext())
{
var welcomeSnippet = "test";
var articles = db.Posts.Where(p => p.DateOfPublish <= DateTime.Now).Take(5).ToList();
return View(new HomeViewModel()
{
Articles = articles,
WelcomeSnippet = welcomeSnippet
});
}
}
该视图包含以下代码:
<%foreach (var item in Model.Articles)
{%>
<div class="article" id="<%=item.PostID %>">
<!-- some properties -->
<div class="tags">tags: <i><%foreach (var tag in item.PostTags.ToList())
{ %><%=Html.Encode(tag.Tag.TagName.Trim())%> <%} %></i>
</div>
</div>
<% } %>
我正在访问 item.PostTags
,它是通过我的 DataContext 获取的。在这里,我本质上使用的是延迟加载,但我收到一个错误:当列出这些 PostTags 时,我的 DataContext 已经被释放。
如何在释放 DataContext 之前加载此类数据?
I have an ASP.NET MVC 2 action that looks like this:
public ActionResult Index()
{
using(var db = new MyDataContext())
{
var welcomeSnippet = "test";
var articles = db.Posts.Where(p => p.DateOfPublish <= DateTime.Now).Take(5).ToList();
return View(new HomeViewModel()
{
Articles = articles,
WelcomeSnippet = welcomeSnippet
});
}
}
The view includes the following code:
<%foreach (var item in Model.Articles)
{%>
<div class="article" id="<%=item.PostID %>">
<!-- some properties -->
<div class="tags">tags: <i><%foreach (var tag in item.PostTags.ToList())
{ %><%=Html.Encode(tag.Tag.TagName.Trim())%> <%} %></i>
</div>
</div>
<% } %>
I'm accessing item.PostTags
, which is obtained through my DataContext. Here, I'm essentially using lazy-loading, but I'm getting an error: my DataContext is already disposed when it comes time to list those PostTags.
How can I load such data before my DataContext is disposed?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
两个选项:
1)手动处理 DC(例如 Global.asax 中的 Application_EndRequest)
2)在控制器中急切加载
item.Tags
:我会选择选项 2,因为选项 1 在不使用DI 容器。 (你显然没有使用)。
编辑
抱歉 - 我以为您使用的是实体框架,这里是“渴望加载”的 L2SQL 等效项:
您需要使用 DataLoadOptions
Two options:
1) Manually Dispose of DC (e.g Application_EndRequest in Global.asax)
2) Eager load
item.Tags
in Controller:I would go option 2, as option 1 is risky without the use of a DI container. (which your obviously not using).
EDIT
Sorry - i thought you were using Entity Framework, here is the L2SQL equivalent of "eager loading":
You need to use DataLoadOptions