Models in Practice

In Visual Studio, the Models folder contains the classes of the application model.

These files are typically automatically generated, but of course they can be manually created through right-clicking the Models folder and selecting Add > Class.

Assume a class with the name “Sneakers.cs” exists. The following properties could be added to the Sneaker class:

using System;
namespace MvcSneakers.Models
{
	public class Sneaker
	{
	public int ID { get; set; }
	public string Name { get; set; }
	public DateTime ReleaseDate { get; set; }
	public string Sport { get; set; }
	public decimal Price { get; set; }
	}
}

The Sneaker class represents sneakers in a database, and each Sneaker object instance corresponds to a database table row. Each property of the Sneaker class maps to a column. The following SneakerDBContext class must be added to support this:

using System;
using System.Data.Entity;
namespace MvcSneakers.Models
{
	public class Sneaker
	{
	public int ID { get; set; }
	public string Name { get; set; }
	public DateTime ReleaseDate { get; set; }
	public string Sport { get; set; }
	public decimal Price { get; set; }
	}
	public class SneakerDBContext : DbContext
	{
	public DbSet<Sneaker> Sneakers { get; set; }
	}
}

The following line of code allows DbContext and DbSet to be referenced:

using System.Data.Entity;

The SneakerDBContext class represents the Entity Framework sneaker database context. This tool manages the collection, storage, and modification of Sneaker class instances in the database. The SneakerDBContext comes from the DbContext base class the Entity Framework provides, and the using statement allows the application access to it.

Adding a controller to the model only requires navigating to the Controllers folder > Add > Controller.