我想在我的主页上显示:所有部分(本节中的所有链接类别和最新的新闻记录)。 请帮我完成我的代码。 非常感谢你。
我的DbContext类:
public partial class xxDbContext : DbContext
{
public xxDbContext()
: base("name=xxDbConnection") { }
public virtual DbSet<Category> Categories { get; set; }
public virtual DbSet<Section> Sections { get; set; }
public virtual DbSet<News> News { get; set; }
}
public partial class Section
{
public int Id { get; set; }
public string Name { get; set; }
public virtual List<Category> Categories { get; set; }
}
public partial class Category
{
public int Id { get; set; }
public int SectionId { get; set; }
public string Name { get; set; }
public virtual Section Section { get; set; }
}
public partial class News
{
public int Id { get; set; }
public int CateId { get; set; }
public string Title { get; set; }
public string Content { get; set; }
}
我的控制器
public ActionResult NewsInSec()
{
var model = db.Sections.Where(m => m.Publish).ToList();
return PartialView("NewsInSec", model);
}
我的观点
@model IEnumerable<xx.Models.Section>
<div>
@foreach (var sect in Model)
{
<ol class="breadcrumb">
<li><a href="/Section/@sect.Id">@sect.Name</a></li>
@foreach (var cate in sect.Categories)
{
<li><a href="/Cate/@cate.Id">@cate.Name</a></li>
}
</ol>
**foreach (var item in sect.Categories.SelectMany(c => c.News).Where(c => c.Publish).OrderByDescending(c => c.CreateDate).Take(4).ToList())
{
<div>
@* News title*@
<h4><a href="#">@item.Title</a></h4>
<img src="~/img/news/@item.Image" />
@*Content of lastest news*@
<p>@item.NewsContent</p>
<p><a href="#">@item.Title</a></p>
</div>
}**
}
最后,我想将部分,美食,新闻显示为我附上的照片。 请帮助我再次查看并修复我的代码?非常感谢和感谢。
答案 0 :(得分:1)
您可以在类别中添加导航属性,以便轻松访问新闻。
public partial class Category
{
public int Id { get; set; }
public int SectionId { get; set; }
...
public virtual List<News> News { get; set; }
}
并选择最新消息:
@foreach (var cate in sect.SelectMany(s=>s.Categories.SelectMany(c=>c.News))
.OrderByDescending(n=>n.ID).Take(5))
{
<div>
// Title of lastest news
<h3></h3>
<img src="~/img/...." />
// Content of lastest news
<p></p>
</div>
}
注意:更正确的方法是在Controller中查找最新消息并在ViewModel中包含结果,如下所示:
public class SomeViewModel
{
public IEnumerable<Section> Sections {get;set;}
public IEnumerable<News> LastNews{get;set;}
}
在控制器中填写此模型并传入视图。