Reputation: 176
I'm building a pretty basic site in MVC 4 & Entity 5 CF, got my ViewModels, Automapper and a generic DAL up and running, except I'm stuck on this issue:
Basically, I have three tables; BlogPost, Tags (Contains TagId and Name - just a list of tags e.g. C#, .NET, Ruby etc) and EntryTags (BlogPostId and TagId - a list of BlogPosts and related tags). I've created a ViewModel which gets all the BlogPosts and the related Tags, which works fine except the list of tags only displays the EntryTag ID next to each blog, I'm unsure of how and where exactly to link that to the Tags table to grab the name of the tag.
Example of the models I'm using:
BlogPost model:
public abstract class BlogPost
{
[Key, DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
public int BlogPostId { get; set; }
[Required, MaxLength(20)]
public string Title { get; set; }
[Required]
public string Content { get; set; }
[Required]
public DateTime DateCreated { get; set; }
[Required]
public DateTime DateModified { get; set; }
public virtual ICollection<EntryTag> EntryTags { get; set; }
}
Tag model:
[Table("Tag")]
public class Tag
{
[Key, DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
public int TagId { get; set; }
[Required]
[MaxLength(20)]
public string Name { get; set; }
}
[Table("EntryTag")]
public class EntryTag
{
[Key, DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
public int EntryTagId { get; set; }
[Required]
public Entry Entry { get; set; }
[Required]
public Tag Tag { get; set; }
}
The ViewModel:
public class BlogIndexViewModel
{
public int EntryId { get; set; }
public string Title { get; set; }
public string Content { get; set; }
public DateTime DateCreated { get; set; }
public virtual ICollection<EntryTag> EntryTags { get; set; }
}
The Automapping from the Controller between the Model & ViewModel
IEnumerable<BlogPost> blogPosts = _genericRepository.GetAll();
IEnumerable<BlogIndexViewModel> viewModel = Mapper.Map<IEnumerable<BlogPost>, IEnumerable<BlogIndexViewModel>>(blogPosts);
And the Blog index page:
@Html.DisplayFor(modelItem => item.EntryTags)
Upvotes: 1
Views: 1292
Reputation: 65860
You have to create your EntryTag
class with virtual
navigation properties
is as below.
[Table("EntryTag")]
public class EntryTag
{
[Key, DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
public int EntryTagId { get; set; }
[Required]
public virtual Entry Entry { get; set; }
[Required]
public virtual Tag Tag { get; set; }
}
Upvotes: 2