MVC 3 EF从模型中检索多对一

时间:2012-07-31 17:43:12

标签: asp.net-mvc-3 entity-framework linq-to-entities

我正在创建一个页面,显示在过去7天内创建的6个博客。该博客包含图像和多个评论

以下是博客模型

public class Blog
{
    public int BlogID { get; set; }
    public int likes { get; set; }
    public int ImageID { get; set; }
    public Boolean removed { get; set; }
    public DateTime dte_created { get; set; }
    public DateTime? dte_modified { get; set; }
    public virtual Image Image { get; set; }
    public virtual ICollection<Comment> Comment { get; set; }
}

这是blogContent。

public class Image
{
    public int ImageID { get; set; }
    public string img_path { get; set; }
    public string Description { get; set; }       
    public DateTime dte_created { get; set; }
}

public class Comment
{
    public int CommentID { get; set; }
    public string Commentation { get; set; }
    public int likes { get; set; }
    public int BlogID { get; set; }
    public DateTime dte_created { get; set; }
    public DateTime? dte_modified { get; set; }
    public Boolean removed { get; set; }
    //public virtual int Account_ID { get; set; }
    public virtual Blog Blog { get; set; }
}

这是控制器

private ACaptureDB db = new ACaptureDB();        

public ViewResult Index()
{
    ViewBag.Message = "ArchiCapture";
    var dateCheck = DateTime.Now.AddDays(-7);

    var results = from r in db.Blog
                  where r.dte_created >= dateCheck
                  select r;

    return View(results);
}

和我的观点。

@model IEnumerable<ACapture.Models.Blog>

@{
    ViewBag.Title = "Home Page";
}


<div class="Forum">
    <p>The Forum</p>

    <form class="Forum" runat="server">
            @foreach (var item in Model)
            {

                <div class="ForumChild"><img src="@item.Image.img_path" alt="Not Found" />
                <br />
                    <table>
                        ?????????
                    </table>
                </div>                

            }
    </form>
</div>

如何检索链接到博客的所有评论?

1 个答案:

答案 0 :(得分:2)

您应该能够遍历模型博客对象中的Comments集合:

<table>
    @foreach(var comment in Model.Comments) {
         <tr>
            <td>@comment.Commentation</td>
            ....
         </tr>
    }
</table>