我已经阅读过其他类似的帖子,但仍然不清楚。我希望没有人介意重新唤醒一个主题,而不是让旧的东西死去并希望得到回应。
问题是何时处置 DbContext。这是我的 MVC 应用程序上的控制器示例
public ActionResult Index()
{
using (var db = new TheCurve.Models.TheCurveDb())
{
var result = db.GetTopArticles().ToList();
return View(result);
}
}
在此示例中,Razor 视图会引发异常,因为 DbContext 已因使用块而被释放。
如果我不处理 DbContext,当 Razor 视图尝试访问模型上的属性(例如这段代码)时,它会抛出错误“已经有一个与此命令关联的打开的数据读取器”。
var type = Model.ArticleType.Type;
switch (type)
{
case "Example":
defaultTitleImage = "Content/themes/base/images/example.png";
break;
case "Download":
defaultTitleImage = "Content/themes/base/images/download.png";
break;
case "Link":
defaultTitleImage = "Content/themes/base/images/link.png";
break;
case "Article":
defaultTitleImage = "Content/themes/base/images/article.png";
break;
}
我知道 DbContext 在检索数据后会关闭连接,但这是否意味着它不需要处理?
非常感谢
-编辑
显示文章概述的局部视图。
@model TheCurve.Models.Article
@{
//Shorten description for Article overview
var strDescription = Model.Description.Length > 250 ? Model.Description.Substring(0, 250) + "..." : Model.Description + "...";
//Decide which image to show on overview.
string defaultTitleImage = null;
if (Model.TitleImage == null)
{
var type = Model.ArticleType.Type;
switch (type)
{
case "Example":
defaultTitleImage = "Content/themes/base/images/example.png";
break;
case "Download":
defaultTitleImage = "Content/themes/base/images/download.png";
break;
case "Link":
defaultTitleImage = "Content/themes/base/images/link.png";
break;
case "Article":
defaultTitleImage = "Content/themes/base/images/article.png";
break;
}
}
else
{
defaultTitleImage = Model.TitleImage;
}
}
<article class="clear-fix">
<div class="float-left">
<img src="@defaultTitleImage" alt="The Curve - Article Type"/>
</div>
<div class="float-left articleoverview">
@Html.ActionLink(Model.Title.TrimStart(), "Details","Code", new {articleId = Model.Id}, null)
<p>@strDescription</p>
<p><i>By @Model.Author On @Model.DateCreated.ToString("dd/MM/yyyy")</i></p>
</div>
</article>
这是使用上述部分的 Razor 视图。
@model IEnumerable<TheCurve.Models.Article>
@{
ViewBag.Title = "Code Samples & Technology Blog";
}
<section>
<h3>Currently Viewing Most Recent Entries</h3>
@foreach (var item in Model)
{
@Html.Partial("_ArticleOverview", item)
}
</section>