Adding data model classes
In Solution Explorer, right click the Models folder > Add > Class. Name the class Movie and add the following properties:
using System; namespace MvcMovie.Models { public class Movie { public int ID { get; set; } public string Title { get; set; } public DateTime ReleaseDate { get; set; } public string Genre { get; set; } public decimal Price { get; set; } } }
n addition to the properties you’d expect to model a movie, the ID
field is required by the DB for the primary key.
Build the project.
If you don’t build the app, you’ll get an error in the next section.
We’ve finally added a Model to our MVC app.
Scaffolding a controller
In Solution Explorer, right-click the Controllers folder > Add > Controller.
In the Add Scaffold dialog, tap MVC Controller with views, using Entity Framework > Add.
Complete the Add Controller dialog
- Model class: Movie(MvcMovie.Models)
- Data context class: ApplicationDbContext(MvcMovie.Models)
- Views:: Keep the default of each option checked
- Controller name: Keep the default MoviesController
- Tap Add
The Visual Studio scaffolding engine creates the following:
- A movies controller (Controllers/MoviesController.cs)
- Create, Delete, Details, Edit and Index Razor view files (Views/Movies)
Visual Studio automatically created the CRUD (create, read, update, and delete) action methods and views for you (the automatic creation of CRUD action methods and views is known as scaffolding).
You’ll soon have a fully functional web application that lets you create, list, edit, and delete movie entries.
If you run the app and click on the Mvc Movie link, you’ll get the following errors:
We’ll follow those instructions to get the database ready for our Movie app.
Update the database
Warning
You must stop IIS Express before you update the database.
To Stop IIS Express:
- Right click the IIS Express system tray icon in the notification area
- Tap Exit or Stop Site
- Alternatively, you can exit and restart Visual Studio
- Open a command prompt in the project directory (MvcMovie/src/MvcMovie). Follow these instructions for a quick way to open a folder in the project directory.
- Open a file in the root of the project (for this example, use Startup.cs.)
- Right click on Startup.cs > Open Containing Folder.
- Shift + right click a folder > Open command window here
- Run
cd ..
to move back up to the project directory
- Run the following commands in the command prompt:
dotnet ef migrations add Initial dotnet ef database update