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

Latest commit

 

History

History
185 lines (123 loc) · 6.81 KB

Addamodel-VSMac.md

File metadata and controls

185 lines (123 loc) · 6.81 KB

Add a data model in Visual Studio for Mac

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

Prerequisites

Add a data model

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

  1. In Solution Pad, right-click the RazorPagesMovie project. Select Add > New Folder. Name the folder Models.

  2. Right click the Models folder. Select Add > New Class.

  3. Select General > Empty Class and name the class Movie.

  4. Replace the contents of the Movie.cs file with the following code:

    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 NuGet Sqlite and Entity Framework Core

Now, let's add NuGet package for the Sqlite provider for Entity Framework Core, which will enable you to have a database for your web app.

  1. In Solution Pad, right-click the RazorPagesMovie project and select Manage NuGet Packages.

  2. Search for Microsoft.EntityFrameworkCore.Sqlite.

  3. Check the checkbox for the package and select Add Package.

Repeat these steps to add the following packages:

  • Microsoft.EntityFrameworkCore.Design
  • Microsoft.EntityFrameworkCore.SqlServer
  • Microsoft.VisualStudio.Web.CodeGeneration.Design

Add a database context class

  1. Add a folder named Data.

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

The database context, or DbContext, is a class provided by Entity Framework to facilitate database interactions. Add the following code:

using Microsoft.EntityFrameworkCore;
using RazorPagesMovie.Data;

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 directive 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

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 need to close and reopen the console window to be able to use this tool.

Run the following command:

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

Test your app

  1. Build the application with Build > Rebuild Solution.

  2. Run the application with Debug > Start without Debugging.

  3. Append /movies to the URL in the browser: https://localhost:{port}/movies

  4. Create a new entry with the Create link.

    It works!

  5. Test the Edit, Details and Delete links.

If you get a SQL exception, verify you have run migrations and updated the database.

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