I seem to be having a problem passing related data to my view. I'm creating a simple blog, which has a database architecture of three tables. These are Users, Posts and Comments. For my user profile page I wish to pass all the data from these tables into the user profile view. I used Linq to SQl to create my database model. Here is my attempt at passing in the data using Linq:
public ActionResult NewProfile()
{
var users = from u in db.UserModels
join p in db.PostModels on u.UserId equals p.UserId
where u.UserId == WebSecurity.CurrentUserId
select new Profile { UserModel = u, PostModel = p };
return View(users);
}
This is the code in the receiving view:
@model IEnumerable<MvcBlog.Models.Profile>
@{
ViewBag.Title = "NewProfile";
}
<h2>NewProfile</h2>
@foreach (var item in Model)
{
@item.UserModel.Username
}
Before I tell you what the result was, I think it's important to give you an idea about the data in my database. Currently, I only have three users. Only one of these users (gb201) has created any blog posts. The user gb201 has created a total of two blog posts.
When I run the program, and log in as user gb201, the data that is displayed on the NewProfile page is:
New Profile
gb201
gb201
The view is being passed the data from two tables, however, when I wish to query the user table, it is duplicating the data based on the number of posts for that user. So if a user only had one post, then it would only display once. For the two other users, who haven't posted anything, there is no information displayed on this page.
I'm assuming that my linq code which is querying the database is wrong, however, I can't seem to think what i'm doing wrong. Sorry for the long question, and any help would be grateful.