This has to be pretty simple to do, but I'm not finding a whole lot of examples on it. I am wanting to get all posts with their corresponding tags and display in a view. Basically a simple blog type thing. Here is my code with Models, ViewModel, Controller and View. Everything works minus the tags, so something is obviously wrong with my syntax.
public class MeWallPost
{
public virtual int MeWallPostId { get; set; }
public virtual string PostTitle { get; set; }
public virtual string PostContent { get; set;
public virtual DateTime PublishDate { get; set; }
public virtual ICollection<MeWallPostMeTag> MeWallPostMeTags { get; set; }
}
public class MeTag
{
public virtual int MeTagId { get; set; }
public virtual string Name { get; set; }
public virtual ICollection<MeWallPostMeTag> MeWallPostMeTags { get; set; }
}
public class MeWallPostMeTag
{
[Key, Column(Order = 0)]
public virtual int MeWallPostId { get; set; }
[Key, Column(Order = 0)]
public virtual int MeTagId { get; set; }
public virtual MeWallPost MeWallPost { get; set; }
public virtual MeTag MeTag { get; set; }
}
----
public class MeWallPostViewModel
{
public string PostTitle { get; set; }
public string PostContent { get; set; }
public DateTime PublishDate { get; set; }
private IEnumerable<MeTag> _Tags = new List<MeTag>();
public IEnumerable<MeTag> Tags
{
get { return _Tags; }
set { _Tags = value; }
}
public IEnumerable<MeWallPostViewModel> GetPosts()
{
var db = new DatselleDB();
return from post in db.MeWallPosts
select new MeWallPostViewModel
{
PostTitle = post.PostTitle,
PostContent = post.PostContent,
PublishDate = post.PublishDate,
Tags = post.MeWallPostMeTags.Select(a => a.MeTag)
};
}
}
-----
public ViewResult Index()
{
return View(new MeWallPostViewModel());
}
------
@foreach (var item in Model.GetPosts()) {
<div class="postItem clear">
<h3>@Html.DisplayFor(modelitem => item.PostTitle)</h3>
<span class="date">@Html.DisplayFor(modelitem => item.PublishDate)</span>
<p>@Html.DisplayFor(modelItem => item.PostContent)</p>
@foreach (var tag in Model.Tags) {
@Html.DisplayFor(modelItem => tag.Name.ToString())
}
</div>
}