Visual Studio For Mac Asp.net Mvc

Introduction to ASP.NET Core MVC on macOS, Linux, or Windows.; 2 minutes to read Contributors. In this article. By Rick Anderson. This tutorial will teach you the basics of building an ASP.NET Core MVC web app using Visual Studio Code.

  • Make sure to install the ASP.NET and web development workload 2. Create a new project. Open Visual Studio 2017 and let the fun begin!
  • Developing ASP.NET Applications on a Mac With Visual Studio Code ¶. Start Visual Studio Code; Tap File > Open and navigate to your Empty ASP.NET Core app; From a Terminal / bash prompt, run dotnet restore to restore the project’s dependencies. Alternately, you can enter command shift p in Visual Studio Code and then type dot as shown. You can run commands directly from within Visual Studio.
-->

By Rick Anderson and Tom Dykstra

In this section, you add classes for managing movies in a database. These classes will be the 'Model' part of the MVC app.

You use these classes with Entity Framework Core (EF Core) to work with a database. EF Core is an object-relational mapping (ORM) framework that simplifies the data access code that you have to write.

The model classes you create are known as POCO classes (from Plain Old CLR Objects) because they don't have any dependency on EF Core. They just define the properties of the data that will be stored in the database.

In this tutorial, you write the model classes first, and EF Core creates the database. An alternate approach not covered here is to generate model classes from an existing database. For information about that approach, see ASP.NET Core - Existing Database.

Add a data model class

Right-click the Models folder > Add > Class. Name the file Movie.cs.

Add a file named Movie.cs to the Models folder.

Update the Movie.cs file with the following code:

The Movie class contains an Id field, which is required by the database for the primary key.

The DataType attribute on ReleaseDate specifies the type of the data (Date). With this attribute:

  • The user is not required to enter time information in the date field.
  • Only the date is displayed, not time information.

DataAnnotations are covered in a later tutorial.

Add NuGet packages

From the Tools menu, select NuGet Package Manager > Package Manager Console (PMC).

In the PMC, run the following command:

The preceding command adds the EF Core SQL Server provider. The provider package installs the EF Core package as a dependency. Additional packages are installed automatically in the scaffolding step later in the tutorial.

Run the following .NET Core CLI commands:

The preceding commands add:

  • The Entity Framework Core Tools for the .NET CLI.
  • The EF Core SQLite provider, which installs the EF Core package as a dependency.
  • Packages needed for scaffolding: Microsoft.VisualStudio.Web.CodeGeneration.Design and Microsoft.EntityFrameworkCore.SqlServer.

Create a database context class

A database context class is needed to coordinate EF Core functionality (Create, Read, Update, Delete) for the Movie model. The database context is derived from Microsoft.EntityFrameworkCore.DbContext and specifies the entities to include in the data model.

Create a Data folder.

Add a Data/MvcMovieContext.cs file with the following code:

The preceding code creates a DbSet<Movie> property for the entity set. In Entity Framework terminology, an entity set typically corresponds to a database table. An entity corresponds to a row in the table.

Register the database context

Studio

ASP.NET Core is built with dependency injection (DI). Services (such as the EF Core DB context) must be registered with DI during application startup. Components that require these services (such as Razor Pages) are provided these services via constructor parameters. The constructor code that gets a DB context instance is shown later in the tutorial. In this section, you register the database context with the DI container.

Add the following using statements at the top of Startup.cs:

Add the following highlighted code in Startup.ConfigureServices:

The name of the connection string is passed in to the context by calling a method on a DbContextOptions object. For local development, the ASP.NET Core configuration system reads the connection string from the appsettings.json file.

Add a database connection string

Add a connection string to the appsettings.json file:

Build the project as a check for compiler errors.

Scaffold movie pages

Use the scaffolding tool to produce Create, Read, Update, and Delete (CRUD) pages for the movie model.

In Solution Explorer, right-click the Controllers folder > Add > New Scaffolded Item.

In the Add Scaffold dialog, select MVC Controller with views, using Entity Framework > Add.

Complete the Add Controller dialog:

  • Model class:Movie (MvcMovie.Models)
  • Data context class:MvcMovieContext (MvcMovie.Data)
  • Views: Keep the default of each option checked
  • Controller name: Keep the default MoviesController
  • Select Add

Visual Studio creates:

  • A movies controller (Controllers/MoviesController.cs)
  • Razor view files for Create, Delete, Details, Edit, and Index pages (Views/Movies/*.cshtml)

The automatic creation of these files is known as scaffolding.

For
  • Open a command window in the project directory (The directory that contains the Program.cs, Startup.cs, and .csproj files).

  • On Linux, export the scaffold tool path:

  • Run the following command:

    The following table details the ASP.NET Core code generator parameters:

    ParameterDescription
    -mThe name of the model.
    -dcThe data context.
    -udlUse the default layout.
    --relativeFolderPathThe relative output folder path to create the files.
    --useDefaultLayoutThe default layout should be used for the views.
    --referenceScriptLibrariesAdds _ValidationScriptsPartial to Edit and Create pages

    Use the h switch to get help on the aspnet-codegenerator controller command:

    For more information, see dotnet aspnet-codegenerator

  • Open a command window in the project directory (The directory that contains the Program.cs, Startup.cs, and .csproj files).

  • Run the following command:

    The following table details the ASP.NET Core code generator parameters:

    ParameterDescription
    -mThe name of the model.
    -dcThe data context.
    -udlUse the default layout.
    --relativeFolderPathThe relative output folder path to create the files.
    --useDefaultLayoutThe default layout should be used for the views.
    --referenceScriptLibrariesAdds _ValidationScriptsPartial to Edit and Create pages

    Use the h switch to get help on the aspnet-codegenerator controller command:

    For more information, see dotnet aspnet-codegenerator

You can't use the scaffolded pages yet because the database doesn't exist. If you run the app and click on the Movie App link, you get a Cannot open database or no such table: Movie error message.

Initial migration

Use the EF Core Migrations feature to create the database. Migrations is a set of tools that let you create and update a database to match your data model.

From the Tools menu, select NuGet Package Manager > Package Manager Console (PMC).

In the PMC, enter the following commands:

  • Add-Migration InitialCreate: Generates an Migrations/{timestamp}_InitialCreate.cs migration file. The InitialCreate argument is the migration name. Any name can be used, but by convention, a name is selected that describes the migration. Because this is the first migration, the generated class contains code to create the database schema. The database schema is based on the model specified in the MvcMovieContext class.

  • Update-Database: Updates the database to the latest migration, which the previous command created. This command runs the Up method in the Migrations/{time-stamp}_InitialCreate.cs file, which creates the database.

    The database update command generates the following warning:

    No type was specified for the decimal column 'Price' on entity type 'Movie'. This will cause values to be silently truncated if they do not fit in the default precision and scale. Explicitly specify the SQL server column type that can accommodate all the values using 'HasColumnType()'.

    You can ignore that warning, it will be fixed in a later tutorial.

For more information on the PMC tools for EF Core, see EF Core tools reference - PMC in Visual Studio.

Run the following .NET Core CLI commands:

  • ef migrations add InitialCreate: Generates an Migrations/{timestamp}_InitialCreate.cs migration file. The InitialCreate argument is the migration name. Any name can be used, but by convention, a name is selected that describes the migration. Because this is the first migration, the generated class contains code to create the database schema. The database schema is based on the model specified in the MvcMovieContext class (in the Data/MvcMovieContext.cs file).

  • ef database update: Updates the database to the latest migration, which the previous command created. This command runs the Up method in the Migrations/{time-stamp}_InitialCreate.cs file, which creates the database.

For more information on the CLI tools for EF Core, see EF Core tools reference for .Net CLI.

The InitialCreate class

Examine the Migrations/{timestamp}_InitialCreate.cs migration file:

The Up method creates the Movie table and configures Id as the primary key. The Down method reverts the schema changes made by the Up migration.

Test the app

  • Run the app and click the Movie App link.

    If you get an exception similar to one of the following:

You probably missed the migrations step.

  • Test the Create page. Enter and submit data.

    Note

    You may not be able to enter decimal commas in the Price field. To support jQuery validation for non-English locales that use a comma (',') for a decimal point and for non US-English date formats, the app must be globalized. For globalization instructions, see this GitHub issue.

  • Test the Edit, Details, and Delete pages.

Dependency injection in the controller

Open the Controllers/MoviesController.cs file and examine the constructor:

The constructor uses Dependency Injection to inject the database context (MvcMovieContext) into the controller. The database context is used in each of the CRUD methods in the controller.

Strongly typed models and the @model keyword

Earlier in this tutorial, you saw how a controller can pass data or objects to a view using the ViewData dictionary. The ViewData dictionary is a dynamic object that provides a convenient late-bound way to pass information to a view.

MVC also provides the ability to pass strongly typed model objects to a view. This strongly typed approach enables compile time code checking. The scaffolding mechanism used this approach (that is, passing a strongly typed model) with the MoviesController class and views.

Examine the generated Details method in the Controllers/MoviesController.cs file:

The id parameter is generally passed as route data. For example https://localhost:5001/movies/details/1 sets:

  • The controller to the movies controller (the first URL segment).
  • The action to details (the second URL segment).
  • The id to 1 (the last URL segment).

You can also pass in the id with a query string as follows:

https://localhost:5001/movies/details?id=1

The id parameter is defined as a nullable type (int?) in case an ID value isn't provided.

A lambda expression is passed in to FirstOrDefaultAsync to select movie entities that match the route data or query string value.

If a movie is found, an instance of the Movie model is passed to the Details view:

Examine the contents of the Views/Movies/Details.cshtml file:

The @model statement at the top of the view file specifies the type of object that the view expects. When the movie controller was created, the following @model statement was included:

This @model directive allows access to the movie that the controller passed to the view. The Model object is strongly typed. For example, in the Details.cshtml view, the code passes each movie field to the DisplayNameFor and DisplayFor HTML Helpers with the strongly typed Model object. The Create and Edit methods and views also pass a Movie model object.

Examine the Index.cshtml view and the Index method in the Movies controller. Notice how the code creates a List object when it calls the View method. The code passes this Movies list from the Index action method to the view:

When the movies controller was created, scaffolding included the following @model statement at the top of the Index.cshtml file:

The @model directive allows you to access the list of movies that the controller passed to the view by using a Model object that's strongly typed. For example, in the Index.cshtml view, the code loops through the movies with a foreach statement over the strongly typed Model object:

Because the Model object is strongly typed (as an IEnumerable<Movie> object), each item in the loop is typed as Movie. Among other benefits, this means that you get compile time checking of the code.

Additional resources

Add a data model class

Right-click the Models folder > Add > Class. Name the class Movie.

Add the following properties to the Movie class:

The Movie class contains:

  • The Id field which is required by the database for the primary key.

  • [DataType(DataType.Date)]: The DataType attribute specifies the type of the data (Date). With this attribute:

    • The user is not required to enter time information in the date field.
    • Only the date is displayed, not time information.

DataAnnotations are covered in a later tutorial.

  • Add a class to the Models folder named Movie.cs.

Add the following properties to the Movie class:

The Movie class contains:

  • The Id field which is required by the database for the primary key.

  • [DataType(DataType.Date)]: The DataType attribute specifies the type of the data (Date). With this attribute:

    • The user is not required to enter time information in the date field.
    • Only the date is displayed, not time information.

DataAnnotations are covered in a later tutorial.

Create a Data folder.

Add the following MvcMovieContext class to the Data folder:

The preceding code creates a DbSet property for the entity set. In Entity Framework terminology, an entity set typically corresponds to a database table, and an entity corresponds to a row in the table.

Add a database connection string

Add a connection string to the appsettings.json file:

Add NuGet packages and EF tools

Run the following .NET Core CLI commands:

The preceding commands add Entity Framework Core Tools for the .NET CLI and several packages to the project. The Microsoft.VisualStudio.Web.CodeGeneration.Design package is required for scaffolding.

Register the database context

Add the following using statements at the top of Startup.cs:

Register the database context with the dependency injection container in Startup.ConfigureServices.

Build the project as a check for compiler errors.

Add the following MvcMovieContext class to the Models folder:

The preceding code creates a DbSet property for the entity set. In Entity Framework terminology, an entity set typically corresponds to a database table, and an entity corresponds to a row in the table.

Add a database connection string

Add a connection string to the appsettings.json file:

Add required NuGet packages

Run the following .NET Core CLI command to add SQLite and CodeGeneration.Design to the project:

The Microsoft.VisualStudio.Web.CodeGeneration.Design package is required for scaffolding.

Register the database context

Add the following using statements at the top of Startup.cs:

Register the database context with the dependency injection container in Startup.ConfigureServices.

Build the project as a check for errors.

Scaffold the movie model

In this section, the movie model is scaffolded. That is, the scaffolding tool produces pages for Create, Read, Update, and Delete (CRUD) operations for the movie model.

In Solution Explorer, right-click the Controllers folder > Add > New Scaffolded Item.

In the Add Scaffold dialog, select 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
  • Select Add

Visual Studio creates:

  • An Entity Framework Core database context class (Data/MvcMovieContext.cs)
  • A movies controller (Controllers/MoviesController.cs)
  • Razor view files for Create, Delete, Details, Edit, and Index pages (Views/Movies/*.cshtml)

The automatic creation of the database context and CRUD (create, read, update, and delete) action methods and views is known as scaffolding.

  • Open a command window in the project directory (The directory that contains the Program.cs, Startup.cs, and .csproj files).

  • Install the scaffolding tool:

  • On Linux, export the scaffold tool path:

  • Run the following command:

The following table details the ASP.NET Core code generator parameters:

ParameterDescription
-mThe name of the model.
-dcThe data context.
-udlUse the default layout.
--relativeFolderPathThe relative output folder path to create the files.
--useDefaultLayoutThe default layout should be used for the views.
--referenceScriptLibrariesAdds _ValidationScriptsPartial to Edit and Create pages

Use the h switch to get help on the aspnet-codegenerator controller command:

For more information, see dotnet aspnet-codegenerator

  • Open a command window in the project directory (The directory that contains the Program.cs, Startup.cs, and .csproj files).

  • Install the scaffolding tool:

  • Run the following command:

The following table details the ASP.NET Core code generator parameters:

ParameterDescription
-mThe name of the model.
-dcThe data context.
-udlUse the default layout.
--relativeFolderPathThe relative output folder path to create the files.
--useDefaultLayoutThe default layout should be used for the views.
--referenceScriptLibrariesAdds _ValidationScriptsPartial to Edit and Create pages

Use the h switch to get help on the aspnet-codegenerator controller command:

For more information, see dotnet aspnet-codegenerator

If you run the app and click on the Mvc Movie link, you get an error similar to the following:

You need to create the database, and you use the EF Core Migrations feature to do that. Migrations lets you create a database that matches your data model and update the database schema when your data model changes.

Initial migration

In this section, the following tasks are completed:

  • Add an initial migration.
  • Update the database with the initial migration.
  1. From the Tools menu, select NuGet Package Manager > Package Manager Console (PMC).

  2. In the PMC, enter the following commands:

    The Add-Migration command generates code to create the initial database schema.

    The database schema is based on the model specified in the MvcMovieContext class. The Initial argument is the migration name. Any name can be used, but by convention, a name that describes the migration is used. For more information, see Tutorial: Using the migrations feature - ASP.NET MVC with EF Core.

    The Update-Database command runs the Up method in the Migrations/{time-stamp}_InitialCreate.cs file, which creates the database.

Run the following .NET Core CLI commands:

The ef migrations add InitialCreate command generates code to create the initial database schema.

The database schema is based on the model specified in the MvcMovieContext class (in the Data/MvcMovieContext.cs file). The InitialCreate argument is the migration name. Any name can be used, but by convention, a name is selected that describes the migration.

Examine the context registered with dependency injection

ASP.NET Core is built with dependency injection (DI). Services (such as the EF Core DB context) are registered with DI during application startup. Components that require these services (such as Razor Pages) are provided these services via constructor parameters. The constructor code that gets a DB context instance is shown later in the tutorial.

The scaffolding tool automatically created a DB context and registered it with the DI container.

Examine the following Startup.ConfigureServices method. The highlighted line was added by the scaffolder:

The MvcMovieContext coordinates EF Core functionality (Create, Read, Update, Delete, etc.) for the Movie model. The data context (MvcMovieContext) is derived from Microsoft.EntityFrameworkCore.DbContext. The data context specifies which entities are included in the data model:

The preceding code creates a DbSet<Movie> property for the entity set. In Entity Framework terminology, an entity set typically corresponds to a database table. An entity corresponds to a row in the table.

The name of the connection string is passed in to the context by calling a method on a DbContextOptions object. For local development, the ASP.NET Core configuration system reads the connection string from the appsettings.json file.

You created a DB context and registered it with the DI container.

Test the app

  • Run the app and append /Movies to the URL in the browser (http://localhost:port/movies).

If you get a database exception similar to the following:

You missed the migrations step.

Visual Studio Web Application Tutorial

  • Test the Create link. Enter and submit data.

    Note

    You may not be able to enter decimal commas in the Price field. To support jQuery validation for non-English locales that use a comma (',') for a decimal point and for non US-English date formats, the app must be globalized. For globalization instructions, see this GitHub issue.

  • Test the Edit, Details, and Delete links.

Examine the Startup class:

The preceding highlighted code shows the movie database context being added to the Dependency Injection container:

  • services.AddDbContext<MvcMovieContext>(options => specifies the database to use and the connection string.
  • => is a lambda operator

Open the Controllers/MoviesController.cs file and examine the constructor:

The constructor uses Dependency Injection to inject the database context (MvcMovieContext) into the controller. The database context is used in each of the CRUD methods in the controller.

Strongly typed models and the @model keyword

Earlier in this tutorial, you saw how a controller can pass data or objects to a view using the ViewData dictionary. The ViewData dictionary is a dynamic object that provides a convenient late-bound way to pass information to a view.

MVC also provides the ability to pass strongly typed model objects to a view. This strongly typed approach enables better compile time checking of your code. The scaffolding mechanism used this approach (that is, passing a strongly typed model) with the MoviesController class and views when it created the methods and views.

Examine the generated Details method in the Controllers/MoviesController.cs file:

The id parameter is generally passed as route data. For example https://localhost:5001/movies/details/1 sets:

  • The controller to the movies controller (the first URL segment).
  • The action to details (the second URL segment).
  • The id to 1 (the last URL segment).

You can also pass in the id with a query string as follows:

https://localhost:5001/movies/details?id=1

The id parameter is defined as a nullable type (int?) in case an ID value isn't provided.

Visual Studio For Mac Tutorial

A lambda expression is passed in to FirstOrDefaultAsync to select movie entities that match the route data or query string value.

If a movie is found, an instance of the Movie model is passed to the Details view:

Examine the contents of the Views/Movies/Details.cshtml file:

By including a @model statement at the top of the view file, you can specify the type of object that the view expects. When you created the movie controller, the following @model statement was automatically included at the top of the Details.cshtml file:

This @model directive allows you to access the movie that the controller passed to the view by using a Model object that's strongly typed. For example, in the Details.cshtml view, the code passes each movie field to the DisplayNameFor and DisplayFor HTML Helpers with the strongly typed Model object. The Create and Edit methods and views also pass a Movie model object.

Examine the Index.cshtml view and the Index method in the Movies controller. Notice how the code creates a List object when it calls the View method. The code passes this Movies list from the Index action method to the view:

When you created the movies controller, scaffolding automatically included the following @model statement at the top of the Index.cshtml file:

The @model directive allows you to access the list of movies that the controller passed to the view by using a Model object that's strongly typed. For example, in the Index.cshtml view, the code loops through the movies with a foreach statement over the strongly typed Model object:

Because the Model object is strongly typed (as an IEnumerable<Movie> object), each item in the loop is typed as Movie. Among other benefits, this means that you get compile time checking of the code:

Additional resources