0

So I am working on a self made forum (ASP.net MVC4) and I am currently displaying all the forums, in the controller I do this easy query:

return View(db.Forums.ToList());

But now I want to be able to also include the top post. (a Forum entity has a collection of Post, Post has a Date, I want to order by that and then do a take(1)).

I try something like:

return View(db.Forums.Include(z=>z.Posts.OrderBy(x=>x.Date).Take(1)).ToList());

Then I get the error:

The Include path expression must refer to a navigation property defined on the type. Use dotted paths for reference navigation properties and the Select operator for collection navigation properties. Parameter name: path

PS: here is the current view

@model IEnumerable<MyProject.Data.Forum>

@{
    ViewBag.Title = "Forum Index";
}

<h2>Forums</h2>

<table class="Forum">
    <tbody>
    <tr>Main forums</tr>
    @foreach (var item in Model)
    {
        <tr class="ForumItem">
            <td><a href="Index?id=@item.Id">X</a></td>
            <td><p><a href="Index?id=@item.Id">@item.Name</a></p><span>@item.Description</span></td>
            <td>@item.PostCount</td>
            @foreach(var post in item.Posts)
            {
                <td>@post.Title</td>
            }
        </tr>
    }
    </tbody>
</table>

Anyone knows a solution for this?

Maximc
  • 1,722
  • 1
  • 23
  • 37

2 Answers2

2

You could do it like this:

return View(db.Forums.Select(f => new {
      Forum = f, 
      FirstPost = f.Posts.OrderBy(x=>x.Date).First() }
   ).ToList()
); 
cjk
  • 45,739
  • 9
  • 81
  • 112
  • doesnt work it doesn t know first post, I then have to make a FirstPost property on the class to make it work? – Maximc Oct 11 '12 at 11:49
  • Yes, this returns a new anonymous class that contains a Forum property and a Firstpost property. This will require changes to how you use the data that is returned. – cjk Oct 11 '12 at 11:53
  • (I changed it to firstordefeault since not all forums got a post already)I now get error: The model item passed into the dictionary is of type 'System.Collections.Generic.List`1[<>f__AnonymousType5`2[Smartp1ck.Data.Forum,Smartp1ck.Data.Post]]', but this dictionary requires a model item of type 'System.Collections.Generic.IEnumerable`1[Smartp1ck.Data.Forum]'. – Maximc Oct 11 '12 at 11:55
  • oke I added my view in it, how should I change the Model because @model IEnumerable is wrong ofc? – Maximc Oct 11 '12 at 12:09
1

I think the error "...Include path expression must refer to a navigation property..." complains that z.Posts.OrderBy is not a navigation property.

Please refer the following page.

Entity Framework, MVC 3, OrderBy in LINQ To Entities

Community
  • 1
  • 1
Jomy John
  • 6,308
  • 4
  • 28
  • 32