我正在尝试创建一个包含可以发表评论的新闻的网站。我一直在关注pluralsight.com的指南,我已经按照信函指南中的内容进行了操作,但是当我调试并在运行时查看模型内部的内容时,评论不包括在内。
我的数据库课程:
public class ProjectDB {
public DbSet<ContentNode> ContentNodes{ get; set; }
public DbSet<Comment> Comments { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
modelBuilder.Entity<ContentNode>()
.Property(n => n.ID).HasColumnName("NodeID");
modelBuilder.Entity<ContentNode>()
.HasMany(node => node.Comments)
.WithRequired(comment => comment.Node);
}
}
涉及的模型:
public class ContentNode : Node
{
public ContentType ContentType { get; set; }
public ContentCategory Category { get; set; }
public ICollection<Comment> Comments { get; set; }
public ContentNode()
{
Comments = new List<Comment>();
}
}
public class Comment
{
public int ID { get; set; }
public ContentNode Node { get; set; }
public string Body { get; set; }
}
从数据库中提取新闻文章并将其发送到视图的控制器方法
[GET("frettir/{year}/{month}/{day}/{title}")]
public ActionResult GetArticle( int year, int month, int day, string title)
{
var model = (from f in _db.ContentNodes
where f.dateCreated.Year == year &&
f.dateCreated.Month == month &&
f.dateCreated.Day == day &&
f.Title == title &&
f.ContentType.ID == 1
select f).Single();
return View(model);
}
最后是观点本身:
@model Project.Models.ContentNode
@{
ViewBag.Title = "GetByID";
}
<h2>GetByID</h2>
<fieldset>
<legend>News</legend>
<div class="display-label">
@Html.DisplayNameFor(model => model.Title)
</div>
<div class="display-field">
@Html.DisplayFor(model => model.Title)
</div>
<div class="display-label">
@Html.DisplayNameFor(model => model.Body)
</div>
<div class="display-field">
@Html.DisplayFor(model => model.Body)
</div>
<div class="display-label">
@Html.DisplayNameFor(model => model.dateCreated)
</div>
<div class="display-field">
@Html.DisplayFor(model => model.dateCreated)
</div>
</fieldset>
<p>
@Html.ActionLink("Edit", "Edit", new { id=Model.ID }) |
@Html.ActionLink("Back to List", "Index")
</p>
@foreach (var item in Model.Comments)
{
@Html.Partial("_Comment",item)
}
@Html.ActionLink("New comment", "Create", "Comment", new { NodeID = Model.ID }, null)
我看了几个例子,我已经看了十几次视频指南,看看我做错了什么。我提出的唯一解决方案是将NodeContent表与Comments表一起加入并将其投影到另一个模型中,但是从我可以收集的内容中不应该这样做。
感谢任何帮助。
答案 0 :(得分:2)
var model = _db.ContentNodes
.Include(f => f.Comments) // eager load the child collection
.Single(f => f.dateCreated.Year == year
&& f.dateCreated.Month == month
&& f.dateCreated.Day == day
&& f.Title == title
&& f.ContentType.Id == 1);
答案 1 :(得分:0)
这很可能是因为Entity Framework默认启用了延迟加载。您可以使用First
方法而不是Single
方法明确强制查询运行:
var model = (from f in _db.ContentNodes
where f.dateCreated.Year == year &&
f.dateCreated.Month == month &&
f.dateCreated.Day == day &&
f.Title == title &&
f.ContentType.ID == 1
select f).First();
return View(model);