Exercise Solutions: OMG the ORM!

Line numbers are for reference. They may not match your code exactly.

The EventCategory Class

EventCategory needs to have the following:
  1. An Id property of type int.
  2. A Name property of type string.
  3. A no arg constructor.
  4. A constructor that sets the value of Name.

EventCategory represents data that will be stored in our database.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
   public class EventCategory
   {
      public string Name { get; set; }

      public int Id { get; set; }

      public EventCategory(string name)
      {
         Name = name;
      }

      public EventCategory()
      {
      }
   }

Return to exercises

Adding to DbContext

Once you have created EventCategory, you need to add to EventDbContext to set up a table in the database for storing categories

public DbSet<EventCategory> Categories { get; set; }

Return to exercises

The EventCategoryController Class

Create EventCategoryController in the Controllers directory. To get our action methods working, we also need a variable of type EventDbContext.

Index() needs to do the following:
  1. Responds to GET requests at EventCategory/Index and returns a view called Index.cshtml.
  2. Pass the DbContext category values as a list into the view template as a model
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
   public class EventCategoryController : Controller
   {
      private EventDbContext context;

      public EventCategoryController(EventDbContext dbContext)
      {
         context = dbContext;
      }

      // GET: /<controller>/
      [HttpGet]
      public IActionResult Index()
      {
         ViewBag.title = "All Categories";
         List<EventCategory> categories = context.Categories.ToList();
         return View(categories);
      }
   }

Return to exercises

Adding a View

Index.cshtml needs to have the following:
  1. Use the list passed in from the action method in the controller as a model to populate the view.
  2. An h1 with an appropriate heading for the page.
  3. A table that will display all of the category names of the event categories stored in our database.
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
   @model List<CodingEventsDemo.Models.EventCategory>

   <h1>All Event Categories</h1>

   <table>
      <tr>
      <th>Category Name</th>
      </tr>
      @foreach(EventCategory category in Model)
      {
         <tr>
               <td>@category.Name</td>
         </tr>
      }
   </table>

Return to exercises