標籤

2020年3月11日 星期三

ASP.NET Core - Add a model

᳓前言

᳓重點整理

  • 新增一個Model
  • 新增與Model對應的Scaffold
  • 初始化Migration

*重點1. 新增一個Model

  • 右鍵點擊RazorPagesMovie專案 > 加入 > 新增資料夾,命名為Models
  • 右鍵點擊Models資料夾 > 加入 > 新增項目 > Class,命名為Movie
  • 在Movie class中加入以下的屬性
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations; // []
using System.Linq;
using System.Threading.Tasks;
namespace RazorPagesMovie.Models
{
public class Movie
{
public int ID { get; set; } // the primary key
public string Title { get; set; }
// The DataType attribute spedifies the type of the data(Date).
// With this attribute:
// 1. The user is not required to enter time information in the date field.
// 2. Only the date is displayed, not time information.
[DataType(DataType.Date)]
public DateTime ReleaseDate { get; set; }
public string Genre { get; set; }
public decimal Price { get; set; }
}
}
view raw Movie.cs hosted with ❤ by GitHub

*重點2. 新增與Model對應的Scaffold

  • 右鍵點擊Pages資料夾 > 加入 > 新增資料夾,命名為Movies
  • 右鍵點擊Movies資料夾 > 加入 > 新增Scaffold項目 > Razor頁面 > 使用Entity Framework(CRUD)的Razor頁面
  • 在模型類別(M)欄位選擇Movie(RazorPagesMovie.Models)、在資料內容類別(D)欄位選擇RazorPagesMovie.Models.RazorPagesMovieContext > 新增
  • 加入完成後會自動建立下列資料夾及檔案:
    • Data/RazorPagesMovieContext.cs
    • Pages/Movies/Create, Delete, Details, Edit, Index
  • 加入完成後會更新以下檔案:
    • Startup.cs(※新增services.AddDbContext<RazorPagesMovieContext>(...))
    • appsettings.json(※新增ConnectionStrings,可修改自動命名的資料庫名稱)

*重點3. 初始化Migration

  • 工具 > NuGet套件管理員 > 套件管理器主控台
  • 分別輸入以下兩個指令(※按下Enter送出並執行指令)
    • Add-Migration InitialCreate(※新增一個命名為InitialCreate的Migration,執行後會於Migrations資料夾建立<time-stamp>_InitialCreate.cs檔案,自動產生用來建立Movie資料表的程式碼)
    • Update-database(※執行<time-stamp>_InitialCreate.cs的Up方法,執行完畢會於C:\使用者\{user}建立資料庫檔案,含.mdf及.ldf)
  • Ctrl+F5執行網頁,於網址輸入https://localhost:{port}/Movies測試網站是否運作正常

沒有留言:

張貼留言