Q:

How to get a related object sorted with Entity Framework for ASP.NET MVC

Having two classes like Blog and Post, in Entity Framework (and LINQ-to-Entities), how can you get the blogs with the posts sorted by date. I was getting the blogs with the posts this way:
from blog in db.BlogSet.Include("Posts") select blog

and now I'm forced to do this:
public class BlogAndPosts {
    public Blog Blog { get; set; }
    public IEnumerable<Post> Posts { get; set; }
}

from blog in db.BlogSet
select new BlogAndPosts () {
    Blog = blog,
    Posts = blog.Posts.OrderByDescending(p => p.PublicationTime)
}

which is very convoluted and ugly. The reason why I'm creating a BlogPosts class is that now, since I have to pass two variables, Blog and Posts, to MVC, I need a view model.
I'm even tempted to try this hack:
from blog in db.BlogSet
select new Blog(blog) {
    Posts = blog.Posts.OrderByDescending(p => p.PublicationTime)
}

but what's the correct way to do it? Is Entity Framework not the way to go with MVC?

A:

I generally create a presentation model type wholly unaware of the Entity Framework and project into that. So I would do something like:
public class PostPresentation {
    public Guid Id { get; set; }
    public string Title { get; set; }
    public DateTime PostTime { get; set; }
    public string Body { get; set; }
}

public class BlogHomePresentation {
    public string BlogName { get; set; }
    public IEnumerable<Post> RecentPosts { get; set; }
}

from blog in db.BlogSet
select new BlogHomePresentation 
{
    BlogName = blog.name,
    RecentPosts = (from p in blog.Posts
                   order by p.PublicationTime desc
                   select new PostPresentation 
                   {
                       Id = p.Id,
                       Title = p.Title,
                       PostTime = p.PublicationTime,
                       Body = p.Body
                   }).Take(10)
}

Does this seem like a lot of work? Consider the advantages:

Your presentation is entirely ignorant of your persistence. Not "ignorant as in having to make all of the properties public virtual," but entirely ignorant.
It is now possible to design the presentation before designing the database schema. You can get your client's approval without doing so much work up front.
The presentation model can be designed to suit the needs of the page. You don't need to worry about eager loading or lazy loading; you just write the model to fit the page. If you need to change either the page or the entity model, you can do either one without affecting the other.
Model binding is easier with simple types. You will not need a custom model binder with this design.

