I have just started using EF Code First to implement a simple blog.
I have a Post object which has a product variable
virtual Product Product { get; set; }
The Product class has a collection of categories
virtual ICollection<Category> Categories { get; set; }
Finally the category has a collection Posts.
virtual ICollection<Post> Posts { get; set; }
This so far has worked well. Now I want to get posts for a particular category. I was originally doing this in my PostRepository by passing in a category Id : such as
public IQueryable<Post> GetPosts(int catId) {
var q = _db.Posts.Select(p => p).Distinct();
if (catId > 0)
q = q.Where(p => p.Product.Categories.Any(c => c.ID == catId));
}
This works great, however I also use a CategoryRepository to get my category. Since the category has a list of products, which in turn has a list of posts, I thought it would be better to just use that, and remove the category from my PostRepository.
However, I have run into an issue. To get the posts, I use this in my controller:
model.Category = _cr.GetCategory(catId);
model.Posts =
new PaginatedList<Post>(model.Category.Products.Select(p => p.Posts)
.AsQueryable(), pageNumber, _defaultPageSize);
The PaginatedList is the one from NerdDinner taking in an IQueryable. Now, this errors because I am passing in a
IQueryable<ICollection<Post>>
So my question is how can I get a IQueryable from my Category entity? I’m sure the answer is simple, but I’ve been trying all kinds of combinations to no avail.
Did you try
.SelectMany(p => p.Posts).AsQueryable()?