Skip to content
This repository has been archived by the owner on Jul 10, 2024. It is now read-only.

Latest commit

 

History

History
184 lines (125 loc) · 6.45 KB

File metadata and controls

184 lines (125 loc) · 6.45 KB

Add a data model in Visual Studio Code

The following tutorial is based on "Get started with ASP.NET Core Razor Pages in Visual Studio Code" from docs.microsoft.com.

Prerequisites

Add a data model

In this section, you're adding classes to manage movies in a database.

  1. Add a folder named Models.

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

  3. Add the following code to the Movie.cs file:

    namespace RazorPagesMovie.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; }
    }

Add Entity Framework NuGet Packages

In the command line, run the following commands (you can open a new Terminal in VS Code via Terminal > New Terminal):

dotnet add package Microsoft.VisualStudio.Web.CodeGeneration.Design
dotnet add package Microsoft.EntityFrameworkCore.Sqlite
dotnet add package Microsoft.EntityFrameworkCore.SqlServer
dotnet add package Microsoft.EntityFrameworkCore.Design
dotnet restore

Add a database context class

  1. Add a folder named Data.

  2. Create a new class named RazorPagesMovieContext.cs in the Models folder.

    The database context, or DbContext, is a class provided by Entity Framework to facilitate database interactions.

    using Microsoft.EntityFrameworkCore;
    using RazorPagesModel.Models;
    
    namespace RazorPagesMovie.Data;
    
    public class RazorPagesMovieContext : DbContext 
    {
        public RazorPagesMovieContext(DbContextOptions<RazorPagesMovieContext> options) 
            : base(options) 
        {
        }
    
        public DbSet<Movie> Movie => Set<Movie>();
    }

The previous code creates a DbSet property for the entity set. An entity set typically corresponds to a database table, and an entity corresponds to a row in the table.

Add a connection string

Open the appsettings.json file and add the RazorPagesMovieContext connection string as shown in the following code:

{
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft.AspNetCore": "Warning"
    }
  },
  "AllowHosts": "*",
  "ConnectionStrings": {
    "RazorPagesMovieContext": "Data Source=MvcMovie.db"
  }
}

Register the database context

  1. Open the Program.cs file.

  2. Add the following using statement at the top of the file.

    using RazorPagesMovie.Data;
  3. Add the following code under builder.Services.AddRazorPages();:

    builder.Services.AddDbContext<RazorPagesMovieContext>(options =>
    options.UseSqlite(builder.Configuration.GetConnectionString("RazorPagesMovieContext") ?? throw new InvalidOperationException("Connection string 'RazorPagesMovieContext' not found.")));

Perform initial migration

Save all files in the project. To run commands to create and manage migrations, you need to install the dotnet ef tool. Do that with the following command in the terminal (you can open a terminal inside of Visual Studio for Mac by right clicking on the project and selecting Open in Terminal).

dotnet tool install --global dotnet-ef

Tip: If dotnet-ef is already installed, you can update it with dotnet tool update --global dotnet-ef.

For more information, see Entity Framework Core tools reference - .NET Core CLI.

In the terminal, run the following commands in the project directory:

dotnet ef migrations add InitialCreate
dotnet ef database update

Commands Explained

Command Description
add package Installs the tools needed.
ef migrations add InitialCreate Generates code to create the initial database schema based on the model specified in 'RazorPagesMovieContext.cs'. InitialCreate is the name of the migrations.
ef database update Creates the database.

Scaffold the movie model

Install the aspnet-codegenerator global tool by running the following command:

dotnet tool install --global dotnet-aspnet-codegenerator

Tip: If dotnet-aspnet-codegenerator is already installed, you can update it with dotnet tool update --global dotnet-aspnet-codegenerator.

Note: You may need to close and reopen the console window to be able to use this tool.

Run the the following commands:

On Windows

dotnet aspnet-codegenerator razorpage -m Movie -dc RazorPagesMovieContext -udl -outDir Pages\Movies --referenceScriptLibraries

On macOS and Linux

dotnet aspnet-codegenerator razorpage -m Movie -dc RazorPagesMovieContext -udl -outDir Pages/Movies --referenceScriptLibraries

Test your app

  1. Run the app by typing the dotnet run command on the terminal.

  2. Launch a browser and go to http://localhost:<port number>/movies.

  3. Create a new entry

    It works!

  4. Test Edit, Details and Delete links.

Extra light read 7 minutes: If you want to read more on pages you just created, see the Part 3, scaffolded Razor Pages in ASP.NET Core article.

NEXT TUTORIAL: Modifying generated pages