dright
dright

Reputation: 653

MVC 3 EF retrieve Many to One from model

I'm creating a page that will display 6 blogs that were created in the passed 7 days. The blog contains an image and multiple comments

Here is the Blog model

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; }
}

And here's the 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; }
}

Here is the controller

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);
}

and my View.

@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>

How would I retrieve all the comments that are linked to the blog?

Upvotes: 0

Views: 82

Answers (1)

mreyeros
mreyeros

Reputation: 4379

You should be able to loop over the Comments collection in your model blog object:

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

Upvotes: 2

Related Questions