I'm trying to retrieve data from a one-to-many relationship, in an ASP.NET MVC application.
Let's say I have two tables Posts and Category with the following attributes:
posts -id -title -category_id
category -id -name -author
I want to grab posts that belong to a category and grab the values of .name and .author from the category. This is what I have in the model:
public IQueryable<Post> GetPosts()
{
return from post in db.Posts
join categories in FindCategories()
on categories.id equals post.category_id
select new
{
title = post.title,
name = categories.name,
author = categories.author
};
}
And in the controller:
public ActionResult Index()
{
var allposts = postRepository.GetPosts().ToList();
return View(allposts);
}
The model complaints that it can't convert and IQueryable of Anonymous type into an IQueryable < Post >. I suspect it's because I'm doing Select new { }, but I'm not sure.
If I do IQueryable only then I don't have the ToList() method available in the view.
So, I'm lost. Can you help? (an by the way, I'm a complete newbie at this asp.net mvc thing.)