If you used wordpress, you will notice how it lets you assign categories to your posts. These categories or Tags are hierarchical and nested. One can assign one or more of these categories to a post (article). Here I’ll show you how to create such functionality and apply that to Questions inside a Quiz.
The Schema
In this example we will see how we can apply the Tags functionality to a Quiz taking website where you have many questions in the database. The Tags (Categories) are assigned to Questions and are of Many to Many (M:M) relationship with Question objects. In our database we will have a table for Questions, a table for Tags and a table called Question_Tags containing the many to many relationship between questions and Tags. Also the Tags table contains ParentTagId foreign key to enable parent-child relationship among the tags. This schema will accommodate multiple hierarchical levels of Tags. For the top level tags, the ParentTagId will be null.
We will use Microsoft ASP.NET MVC 5.2.2 along with Entity framework 6.1.1. We will be creating Model classes for Questions, Tags and Question_Tags. We’ll also create View Model classes: QuestionVM, TagVM to pass it onto our Razor Views.
Model Classes
The Question class which represents the Questions table is as follows;
1 2 3 4 5 6 7 8 9 10 11 |
public class Question { public int QuestionId { get; set; } public string Title { get; set; } public string Content { get; set; } .... public virtual List Question_Tags { get; set; } public void CopyFrom(QuestionVM qvm) { QuestionTypeId = qvm.QuestionTypeId; Title = qvm.Title; ..... Content = qvm.Content; OwnerId = qvm.OwnerId; } } |
Our Tag class is as follows
1 2 3 4 5 6 7 8 |
public class Tag { public int TagId { get; set; } public int? ParentTagId { get; set; } public string TagName { get; set; } public virtual List Question_Tags { get; set; } public virtual Tag ParentTag { get; set; } public virtual List ChildTags { get; set; } } |
Question_Tag class which represents a M:M relationship is as follows:
1 2 3 4 5 6 7 8 9 |
public class Question_Tag { public int Id { get; set; } public int QuestionId { get; set; } public int TagId { get; set; } public virtual Question Question { get; set; } public virtual Tag Tag { get; set; } } |