###### tags: `.NET Core MVC` # ASP.NET Core MVC ## 建立 ASP.NET Core MVC 專案步驟 ### Step1. 新增專案  ### Step2. 選擇 ASP.NET Core Web應用程式(Model-View-Controller)  ### Step3.安裝套件 #### 方案總管的相依性 → 套件 → 管理NuGet套件 * Microsoft.EntityFrameworkCore.SqlServer * Microsoft.EntityFrameworkCore.Tools ## DB first ### 1.在 MS SQL 建立資料庫及資料表 ### 2.套件管理主控台指令 → 選擇預設專案 #### Windows 驗證登入 ``` Scaffold-DbContext "Server=伺服器位置;Database=資料庫;Trusted_Connection=true;TrustServerCertificate=true"Microsoft.EntityFrameworkCore.SqlServer -OutputDir Models -Force -Context Context -NoOnConfiguring ``` #### SQL Server 驗證登入 ``` Scaffold-DbContext "Server=伺服器位置;Database=資料庫;User ID=帳號;Password=密碼;TrustServerCertificate=true" Microsoft.EntityFrameworkCore.SqlServer -OutputDir Models -Force -Context Context -NoOnConfiguring ``` * `-OutputDir` 指定要輸出到專案目錄下哪個資料夾 * `-Force` 宣告要複寫原有檔案 * `-Context` 指定 Context 名稱,沒有指定的話預設為 Database 的名稱 * `-NoOnConfiguring` 不要產生 `DbContext.OnConfiguring` ### 3.新增資料庫連線字串 `appsettings.json` ```json "ConnectionStrings": { "DefaultConnetion": "Server=.\\sqlexpress;Database=[DB];User ID=[帳號];Password=[密碼];TrustServerCertificate=true;" } ``` #### 註冊 DbContext,連線至資料庫 `Programs.cs` ```csharp builder.Services.AddDbContext<ApplicationDbContext>(options => options.UseSqlServer( builder.Configuration.GetConnectionString("DefaultConnetion"))) ``` ## Code first ### 1.新增 Model ```csharp! public class Student { [Display(Name = "編號")] public int Id { get; set; } [Display(Name = "姓名")] [StringLength(50)] public string Name { get; set; } [Display(Name = "住址")] [StringLength(100)] public string Address { get; set; } } ``` ### 2.新增 Context ```csharp! public class DemoDbContext : DbContext { public DemoDbContext(DbContextOptions<DemoDbContext> options) : base(options) { } //Model public DbSet<Student> Students { get; set; } } ``` ### 3.新增資料庫連線字串 `appsettings.json` ```json "ConnectionStrings": { "Default": "Server=.\\sqlexpress;Database=[DB];User ID=[帳號];Password=[密碼];Trusted_Connection=true;TrustServerCertificate=true;" } ``` ### 4.註冊 DbContext,連線至資料庫 `Programs.cs` ```csharp builder.Services.AddDbContext<DemoDbContext>(options => options.UseSqlServer( builder.Configuration.GetConnectionString("Default"))) ``` ### 5.執行 migration 指令 #### Step1. 選擇工具(Tools) → NuGet 套件管理員 → 套件管理主控台叫出 Package Manager Console。 #### Step2. `add-migration [移轉名稱]` 產生資料庫變更記錄:時間戳記_移轉名稱.cs #### Step3. `update-database` 更新資料庫
×
Sign in
Email
Password
Forgot password
or
By clicking below, you agree to our
terms of service
.
Sign in via Facebook
Sign in via Twitter
Sign in via GitHub
Sign in via Dropbox
Sign in with Wallet
Wallet (
)
Connect another wallet
New to HackMD?
Sign up