tags:

views:

38

answers:

3

Hi I have a 2 tables BlogPost and BlogComments

I want to get all BlogPosts that have a state of "published". and get all BlogComments for each post that has a state of "published".

Im using something like this to get the blogposts:

var BlogPosts = (from p in db.BlogPosts where p.State == State.Published select p).ToArray();

but due to the relationship with BlogComments it autiomatically has all the BlogComments (both published and unpublished).

How can I just get the "published" comments for each of the blogposts (i.e the approved ones)

thanks

+4  A: 

Try selecting a new BlogPostViewModel, an analog to BlogPost but with an IEnumerable<BlogComment> instead, with just the blog post data and a collection of published comments.

    select new BlogPostViewModel {
        Title = p.Title,
        Body = p.Body,
        Comments = p.Comments.Where( c => c.Published );
    });

Where BlogPostViewModel is:

public class BlogPostViewModel
{
     public string Title { get; set; }
     public string Body { get; set; }
     public IEnumerable<BlogComment> Comments { get; set; }
}
tvanfosson
ive tried this... return (from p in db.BlogPosts where p.State == State.Published select new BlogPost { Title = p.Title, Body = p.Body, BlogComments = p.BlogComments.Where(c => c.State == State.Published) }).ToArray();but getting cannot convert ienumerable to entityset...:(
raklos
The I would suggest a separate ViewModel type that's an analog to BlogPost that has the Comments as an `IEnumerable<BlogComment>`
tvanfosson
Could I just change the private EntitySet<BlogComment> _BlogComments; field into an ineumerable in the designer.cs file?
raklos
@raklos -- no you wouldn't want to do that. Any changes you make to the designer go away if you ever change your model. You might be able to add a partial class implementation that uses the EntitySet if available, but allows you to override it, but IMO that's ugly and error prone. A view-specific model is usually the way to go anyway -- give your display logic just the data it needs in the form it needs it. Using a view model decouples the view even further from the data model, since you can change the view model depending on your needs without altering the underlying data model.
tvanfosson
A: 
var BlogPosts = from p in db.BlogPosts where p.State == State.Published select new {
    Post = p,
    Comments = (from c in db.BlogComments where c.State == State.Published && c.Post = p select c)
};
Alxandr
A: 
var publishedComments = db.BlobPosts.Where(p => p.State == State.Published)
                                    .SelectMany(p => p.Comments)
                                    .Where(c => c.State == State.Published);

Sorry for not using the query syntax. Hopefully this will get you on your way though.

NickLarsen