返回筆記列表
/ 筆記詳情
新增記事本資料表 SQL 語法¶
使用 SQL Server 建立記事本資料表 Notes,欄位說明如下:
- Id 欄位為主鍵且自動遞增。
- ndate 為日期時間欄位,預設為當前系統時間 (getdate())。
- content 為記事內容文字,容納最多 300 字。
CREATE TABLE [dbo].[Notes]
(
[Id] INT NOT NULL PRIMARY KEY IDENTITY,
[ndate] DATETIME NULL DEFAULT getdate(),
[content] NVARCHAR(300) NULL
)
此資料表設計適用於儲存簡單的記事與時間戳記。
Entity Framework Core 資料查詢範例¶
- 全部欄位撈取,無篩選條件
var notes = ctx.Notes.ToList();
直接取得 Notes 資料表中所有資料。
- 單一欄位撈取,無篩選條件
var notes = ctx.Notes.Select(x => x.Content).ToList();
只取得 Content 欄位資料。
- 多欄位撈取,可更改欄位名稱
var notes = ctx.Notes.Select(x => new { x.Id, 內容 = x.Content }).ToList();
撈取多個欄位且結果中欄位名稱可自訂(例如將 Content 改為 內容)。
- 有條件篩選及全部欄位
以北風資料庫為例,查詢「台北市」且「北平區」的客戶:
var c = ctx.Customers.Where(x => x.City == "台北市" && x.Region == "北平區").ToList();
- 排序查詢(兩個鍵值排序)
var c = ctx.Customers.OrderBy(x => x.City).ThenByDescending(x => x.Region).ToList();
主鍵值以城市排序,再以區域降冪排序。
刪除資料範例¶
- 刪除單筆資料
先使用 Find(鍵值) 找到該筆資料,接著用 Remove 從 DbContext 移除,最後呼叫 SaveChanges 實際刪除資料。
var n = ctx.Notes.Find(鍵值);
ctx.Notes.Remove(n);
ctx.SaveChanges();
- 刪除多筆資料
使用 Where 找出多筆符合條件的資料,再用 RemoveRange 一次刪除。
var n = ctx.Notes.Where(x => x.Id == 1 || x.Id == 3).ToList();
ctx.Notes.RemoveRange(n);
ctx.SaveChanges();
- 結合刪除與查詢
在 Controller Index(int id) 中,如果傳入了 id,先刪除該資料筆數,之後讀取所有資料並透過 ViewBag 傳到 View:
public IActionResult Index(int id)
{
using (var ctx = new FinalDBContext())
{
if(id != 0)
{
var n = ctx.Notes.Find(id);
ctx.Remove(n);
ctx.SaveChanges();
}
var notes = ctx.Notes.ToList();
ViewBag.notes = notes;
return View();
}
}
Razor View 展示記事本資料¶
頁面中用 foreach 列出所有記事資料(時間、內容),並在每筆記錄後面附上刪除按鈕。刪除按鈕使用 <form> POST 傳送該筆記事的 Id,送到相同的 Index Action。
@{
ViewData["Title"] = "Home Page";
var notes = ViewBag.notes;
}
<div class="text-center">
<div class="container w-75">
<table class="table">
<thead>
<tr>
<th>時間</th>
<th>內容</th>
<th>動作</th>
</tr>
</thead>
<tbody>
@foreach(var n in notes)
{
<tr>
<td>@n.Ndate.ToString("yyyy-MM-dd, HH:mm")</td>
<td>@n.Content</td>
<td>
<form action="~/Home/Index" method="post">
<button type="submit" class="btn btn-danger" name="id" value="@n.Id">刪除</button>
</form>
</td>
</tr>
}
</tbody>
</table>
</div>
</div>
這種做法透過表單提交,讓使用者能直接點擊刪除按鈕刪除特定記錄。
相關教學資源¶
- 老師的教學網站(FlipClass):https://flipclass.stust.edu.tw/media/doc/346303
- 範例示範網頁(心情記事本):https://dashboard.coffeeshoptw.com/notes/note/22
這些資源可做為課堂內容的補充與範例參考。
以上為這堂課主要內容精要整理,涵蓋資料表設計、資料查詢與刪除,以及 Razor View 顯示的實作方式,幫助理解 ASP.NET Core MVC 開發中常見的資料存取與呈現流程。若需要更進一步範例與說明,可參考上述教學頁面。
附件 248
WebApplicationEFCore
(1)
WebApplicationEFCore
(5)
wwwroot
(1)
lib
(0)
bootstrap
(1)
dist
(0)
css
(32)
js
(12)
jquery-validation
(1)
jquery
(1)
bin
(0)
Debug
(0)
net8.0
(62)
zh-Hant
(5)
ko
(3)
tr
(4)
fr
(3)
de
(2)
runtimes
(0)
win
(0)
lib
(0)
net6.0
(6)
unix
(0)
pt-BR
(4)
zh-Hans
(4)
ru
(4)
es
(3)
cs
(2)
pl
(4)
ja
(3)
obj
(5)
Debug
(0)
net8.0
(22)
scopedcss
(0)
staticwebassets
(4)
Views
(2)
Models
(10)
vs
(0)
WebApplicationEFCore
(0)
v17
(4)