一、建立 Notes 資料表
在 SQL Server 中,先建立一個簡單的備忘錄資料表 Notes,用來練習 INSERT / SELECT 等基本指令。learn.microsoft+1
-
使用 CREATE TABLE 建立資料表。
-
使用 IDENTITY 做流水號主鍵,DEFAULT getdate() 自動寫入建立時間。
範例指令可寫成:
CREATE TABLE [dbo].[Notes]
(
[Id] INT NOT NULL PRIMARY KEY IDENTITY,
[ndate] DATETIME NULL DEFAULT getdate(),
[content] NVARCHAR(300) NULL
);
執行後,dbo 底下會多出 Notes 資料表,之後可以用 EF Core 做對應模型來練習 CRUD。learn.microsoft
二、在 SQL Server 建立與連接資料庫
這一段說明如何在 Visual Studio/SSDT 介面中建立 Northwind 資料庫,並準備給 EF Core 使用。marcus116.blogspot+1
-
開啟 SQL Server 物件總管
-
在 Visual Studio 上方選單:檢視 → SQL Server 物件總管。
-
在左側 SQL Server 節點上按右鍵,可選「加入 SQL Server」或「中斷連接」,設定你的伺服器連線。
-
-
用 SQL 指令建立 Northwind
-
在 SQL Server 物件總管中,對你的伺服器按右鍵 → 新增查詢。
-
將 Northwind 的 .sql 腳本內容貼入查詢視窗,按執行,建立所有資料表與資料。jetbrains
-
-
用附加方式加入現有資料庫檔案
-
檢視 → 資料庫總管 → 資料連接 → 加入連接。
-
選擇「Microsoft SQL Server 資料庫檔案」,指定 .mdf 檔,即可將現有的 Northwind 加入到工具中。uuu
-
完成後,SQL Server 中已經有 Northwind 與 Notes,可以進入 EF Core 步驟。
三、在專案安裝 Entity Framework Core 套件
Entity Framework Core 是一套物件關聯對應(O/R Mapping)工具,能用 C# 類別代表資料表,而不是直接手寫 SQL。uuu+1
-
在 Visual Studio:工具 → NuGet 套件管理員 → 管理解決方案的 NuGet 套件。
-
切到「瀏覽」頁籤並安裝:
-
Microsoft.EntityFrameworkCore.SqlServer
-
Microsoft.EntityFrameworkCore.Tools
-
因為教室環境使用 .NET 8.0 SDK,請選擇 9.0.xx 對應版本;若要用最新 EF Core 版本,需先更新 .NET SDK 版本。marcus116.blogspot
四、用 Scaffold-DbContext 反向產生模型與 Context
接下來用「資料庫優先(Database First)」方式,從現有的 Northwind 資料庫自動產生 C# 類別與 DbContext。jetbrains+1
-
開啟套件管理器主控台
-
工具 → NuGet 套件管理員 → 套件管理器主控台。
-
-
輸入反向工程指令(範例)
Scaffold-DbContext `
-Connection "Server=(localdb)\MSSQLLocalDB;Database=Northwind;Trusted_Connection=True;" `
Microsoft.EntityFrameworkCore.SqlServer `
-OutputDir Models `
-Force `
-Context NorthwindDBContext
-
Server:本機 LocalDB 伺服器 (localdb)\MSSQLLocalDB。
-
Database:Northwind。
-
Trusted_Connection=True 表示使用 Windows 登入,可省略 User ID / Password。
-
-OutputDir 指定資料表模型類別輸出到 Models 資料夾。
-
-Context 指定 DbContext 類別名稱為 NorthwindDBContext。uuu+1
執行後,專案會多出一個 NorthwindDBContext 類別以及多個資料表對應的模型(Customers、Orders、Products 等),之後控制器就能透過它存取資料庫。jetbrains
五、在控制器使用 DbContext 讀取資料
所有範例都遵守同一個模式:建立 DbContext → 對 context.資料表 操作 → ToList() 取得清單 → 傳給 View。uuu+1
基本範例:取得所有客戶資料 Customers
public IActionResult Index()
{
using (var ctx = new NorthwindDBContext())
{
List<Customer> c = ctx.Customers.ToList();
return View(c);
}
}
-
ctx.Customers 代表 Customers 資料表。
-
ToList() 將查詢結果轉成 List。
-
View(c) 將資料清單傳入 Index.cshtml。
在 Index.cshtml 中,宣告模型並顯示:
@model List
| 名稱 | 縣市 | 地址 | 聯絡人 |
|---|---|---|---|
| @c.CompanyName | @c.City | @c.Address | @c.ContactName |
這樣就完成最基本的「讀取全部資料表資料並顯示在網頁」的流程。jetbrains
六、依條件篩選:Where 與 DropDown 選單
使用 LINQ 的 Where 來實作「依縣市篩選客戶」的功能,搭配下拉選單讓使用者選擇 City。learn.microsoft+1
控制器 Index 動作(帶 city 參數):
public IActionResult Index(string city)
{
using (var ctx = new NorthwindDBContext())
{
var cities = ctx.Customers
.Select(x => x.City)
.Distinct()
.ToList();
var customers = ctx.Customers
.Select(x => new {
公司名稱 = x.CompanyName,
x.Address,
x.City,
x.ContactName,
x.Phone
})
.Where(x => x.City == city)
.ToList();
ViewBag.customers = customers;
ViewBag.cities = cities;
return View();
}
}
-
Select(x => x.City).Distinct() 先取出所有城市再去除重複。
-
Where(x => x.City == city) 篩選某一個城市的客戶。
Index.cshtml 畫面:
@{
var cities = ViewBag.cities as List;
var customers = ViewBag.customers;
}
| 公司名稱 | 聯絡人 | 縣市 | 地址 | 電話 |
|---|---|---|---|---|
| @c.公司名稱 | @c.ContactName | @c.City | @c.Address | @c.Phone |
這樣就完成「選擇縣市 → 顯示指定城市客戶資料」的互動式查詢畫面。jetbrains
七、選取部分欄位與計算欄位(Select)
實務上常常只需要部分欄位,或需要額外的計算欄位,可以用 Select 搭配匿名型別達成。learn.microsoft+1
-
取出產品表 ProductName 與 UnitPrice 欄位:
using (var ctx = new NorthwindDBContext())
{
var data = ctx.Products
.Select(x => new { x.ProductName, x.UnitPrice })
.ToList();
return View(data);
}
-
修改欄位顯示名稱(匿名型別自訂屬性名稱):
using (var ctx = new NorthwindDBContext())
{
var data = ctx.Products
.Select(x => new {
產品名稱 = x.ProductName,
單價 = x.UnitPrice
})
.ToList();
return View(data);
}
-
選取計算欄位,例如訂單明細金額 = 數量 × 單價 × (1 − 折扣):
using (var ctx = new NorthwindDBContext())
{
var data = ctx.OrderDetails
.Select(x => new {
x.Quantity,
x.UnitPrice,
x.Discount,
金額 = Convert.ToSingle(x.Quantity) *
Convert.ToSingle(x.UnitPrice) *
(1 - x.Discount)
})
.ToList();
return View(data);
}
這些 Select 操作對應到 SQL 的 SELECT 子句:指定欄位與運算欄位,用 LINQ 寫起來更直觀。learn.microsoft
八、Distinct、OrderBy、GroupBy 等常用查詢
SQL 中常見的 GROUP BY、ORDER BY、DISTINCT 在 LINQ 中分別對應 GroupBy、OrderBy、Distinct 等方法。w3schools+2
-
取得不重複的國家列表(Distinct):
using (var ctx = new NorthwindDBContext())
{
var countries = ctx.Customers
.Select(x => x.Country)
.Distinct()
.ToList();
return View(countries);
}
-
篩選德國客戶(Where):
using (var ctx = new NorthwindDBContext())
{
var germanCustomers = ctx.Customers
.Where(x => x.Country == "Germany")
.ToList();
return View(germanCustomers);
}
-
排序與群組(OrderBy / GroupBy)概念:
-
context.資料表.OrderBy(x => x.欄位) 對應 SQL 的 ORDER BY 欄位。
-
context.資料表.GroupBy(x => x.欄位) 對應 SQL 的 GROUP BY 欄位。
-
GroupBy(x => new { 名稱 = x.欄位 }) 可同時依多個欄位分組,類似 SQL 中 GROUP BY 欄位1, 欄位2。digitalocean+2
-
了解這些對應關係,可以更輕鬆從 LINQ 推回 SQL 的執行邏輯。
九、練習題:Products、Orders、Employees
以下練習可以放在 TinyMCE 編輯器中當作課堂作業步驟。
-
取得所有產品資料 Products:
控制器:
public IActionResult Index()
{
using (var ctx = new NorthwindDBContext())
{
var p = ctx.Products.ToList();
return View(p);
}
}
View(Index.cshtml):
@model List
| 產品名稱 | 供應商編號 | 單價 | 庫存 |
|---|---|---|---|
| @p.ProductName | @p.SupplierId | @p.UnitPrice | @p.UnitsInStock |
-
取得所有訂單資料 Orders:
-
請在控制器中撰寫 var o = ctx.Orders.ToList();
-
建立對應的 Index.cshtml,顯示訂單編號、客戶編號、員工編號、訂單日期等欄位。
-
-
取得所有員工資料 Employees:
控制器:
public IActionResult Index()
{
using (var ctx = new NorthwindDBContext())
{
var e = ctx.Employees.ToList();
return View(e);
}
}
View(卡片顯示):
@model List
@e.LastName, @e.FirstName
@e.Address
@e.HomePhone
這些練習涵蓋了 EF Core 中最常用的 ToList() 查詢與 View 資料綁定流程。uuu+1
十、CRUD 方法與 Join 進階查詢
EF Core 提供一組標準方法對應新增、更新、刪除與儲存動作。uuu+1
常見方法對照:
-
Add / AddAsync / AddRange / AddRangeAsync:新增資料,需搭配 SaveChanges() 或 SaveChangesAsync()。
-
Update / UpdateRange:更新資料後,呼叫 SaveChanges()。
-
Remove / RemoveRange:刪除資料後,呼叫 SaveChanges()。
-
SaveChanges / SaveChangesAsync:將變更寫入資料庫。
此外還可以使用 Join 撰寫多表查詢,對應到 SQL 的 INNER JOIN。learn.microsoft+1
範例 1:Authors 與 Books 兩表 Join
using (var context = new BookStore())
{
var data = context.Authors
.Join(
context.Books,
author => author.AuthorId,
book => book.Author.AuthorId,
(author, book) => new
{
BookId = book.BookId,
AuthorName = author.Name,
BookTitle = book.Title
}
)
.ToList();
}
範例 2:三表 Join(Authors、AuthorBiographies、Books)
using (var context = new BookStore())
{
var authorsData = context.Authors
.Join(
context.AuthorBiographies,
author => author.AuthorId,
authorBio => authorBio.AuthorBiographyId,
(author, authorBio) => new
{
AuthorId = author.AuthorId,
Name = author.Name,
Biography = authorBio.Biography
}
)
.Join(
context.Books,
author => author.AuthorId,
book => book.BookId,
(author, book) => new
{
AuthorId = author.AuthorId,
Name = author.Name,
Biography = author.Biography,
BookTitle = book.Title
}
)
.ToList();
}
這些 Join 寫法在 LINQ 中對應 SQL JOIN 子句,是從多個資料表組合資料的重要技巧。learn.microsoft+1
... - https://learn.microsoft.com/en-us/sql/t-sql/queries/select-group-by-transact-sql?view=sql-server-ver17
- https://learn.microsoft.com/zh-tw/sql/t-sql/queries/select-examples-transact-sql?view=sql-server-ver17
- https://marcus116.blogspot.com/2019/04/netcore-entity-framework-core-crud-intro.html
- https://www.uuu.com.tw/Public/content/article/20/20200413.htm
- https://blog.jetbrains.com/dotnet/2023/07/20/reverse-engineering-existing-databases-with-entity-framework-core/
- https://www.w3schools.com/sql/sql_groupby.asp
- https://www.digitalocean.com/community/tutorials/how-to-use-groupby-and-orderby-in-sql
- https://www.tiny.cloud/docs/tinymce/latest/add-css-options/
- https://www.tiny.cloud/blog/tinymce-css-and-custom-styles/
- https://www.tiny.cloud/docs/tinymce/latest/editor-content-css/
- https://stackoverflow.com/questions/17701783/tinymce-multiple-css-classes
- https://www.tiny.cloud/blog/css-hacks/
- https://www.tiny.cloud/docs/tinymce/latest/content-formatting/
- https://ithelp.ithome.com.tw/m/articles/10262110
- https://forum.backdropcms.org/forum/add-css-classes-tinymce-editor
- https://processwire.com/talk/topic/501-css-classes-in-tinymce/
- https://www.datacamp.com/tutorial/group-by-having-clause-sql
- https://dev.to/codeanddeploy/tinymce-add-customcontent-css-example-5b5i
- https://stackoverflow.com/questions/79632710/how-to-use-windows-authentication-with-the-scaffold-dbcontext-command
- https://stackoverflow.com/questions/43453120/creating-new-table-from-select-statement