4.0 KiB
title | author | description | keywords | ms.author | manager | ms.date | ms.topic | ms.assetid | ms.technology | ms.prod | uid |
---|---|---|---|---|---|---|---|---|---|---|---|
Adding a model | Microsoft Docs | rick-anderson | Add a model to a simple ASP.NET Core app. | ASP.NET Core, | riande | wpickett | 03/30/2017 | article | 8dc28498-00ee-4d66-b903-b593059e9f39 | aspnet | asp.net-core | tutorials/first-mvc-app/adding-model |
[!INCLUDEadding-model]
In Solution Explorer, right click the MvcMovie project > Add > New Folder. Name the folder Models.
In Solution Explorer, right click the Models folder > Add > Class. Name the class Movie and add the following properties:
[!code-csharpMain]
In addition to the properties you'd expect to model a movie, the ID
field is required by the database for the primary key. Build the project. Build the app to verify you don't have any errors.
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 MVC Dependencies dialog, select Minimal Dependencies, and select Add.
Visual Studio adds the dependencies needed to scaffold a controller, but the controller itself is not created. The next invoke of > Add > Controller creates the 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: Select the + icon and add the default MvcMovie.Models.MvcMovieContext
- Views: Keep the default of each option checked
- Controller name: Keep the default MoviesController
- Tap Add
The scaffolding engine creates the following:
- A movies controller (Controllers/MoviesController.cs)
- Create, Delete, Details, Edit and Index Razor view files (Views/Movies)
Scaffolding 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 an error similar to the following:
An unhandled exception occurred while processing the request.
SqlException: Cannot open database "MvcMovieContext-<GUID removed>"
requested by the login. The login failed.
Login failed for user Rick
Add EF tooling
-
In Solution Explorer, right click the MvcMovie project > Edit MvcMovie.csproj.
-
Add the
"Microsoft.EntityFrameworkCore.Tools.DotNet"
NuGet package:
[!code-xmlMain]
Note: The version numbers shown above were correct at the time of writing.
[!INCLUDEadding-model]
Additional resources
[!div class="step-by-step"] Previous Adding a View