在你的ASP.NET MVC項目中創建一個新的C#類別,例如Student。
public class Student
{
public int Id { get; set; }
public string Name { get; set; }
public int Age { get; set; }
}
namespace WebApplication3_DAY11.Data
{
public class WebApplication3_DAY11Context : DbContext
{
public WebApplication3_DAY11Context() : base("name=WebApplication3_DAY11Context")
{
}
public System.Data.Entity.DbSet<WebApplication3_DAY11.Models.Student> Students { get; set; }
}
}
在控制器中實現以下操作:
新增(Create):新增一個學生到資料庫。
// GET: Students/Create
public ActionResult Create()
{
return View();
}
// POST: Students/Create
// To protect from overposting attacks, enable the specific properties you want to bind to, for
// more details see https://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create([Bind(Include = "Id,Name,Age")] Student student)
{
if (ModelState.IsValid)
{
db.Students.Add(student);
db.SaveChanges();
return RedirectToAction("Index");
}
return View(student);
}
讀取(Read):從資料庫讀取學生列表。
public ActionResult Index()
{
return View(db.Students.ToList());
}
更新(Update):更改某個學生的信息。
// GET: Students/Edit/5
public ActionResult Edit(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
Student student = db.Students.Find(id);
if (student == null)
{
return HttpNotFound();
}
return View(student);
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit([Bind(Include = "Id,Name,Age")] Student student)
{
if (ModelState.IsValid)
{
db.Entry(student).State = EntityState.Modified;
db.SaveChanges();
return RedirectToAction("Index");
}
return View(student);
}
刪除(Delete):從資料庫中刪除某個學生。
// GET: Students/Delete/5
public ActionResult Delete(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
Student student = db.Students.Find(id);
if (student == null)
{
return HttpNotFound();
}
return View(student);
}
// POST: Students/Delete/5
[HttpPost, ActionName("Delete")]
[ValidateAntiForgeryToken]
public ActionResult DeleteConfirmed(int id)
{
Student student = db.Students.Find(id);
db.Students.Remove(student);
db.SaveChanges();
return RedirectToAction("Index");
}
還在努力轉職中
Github https://github.com/qsc811022/WebApplication3_DAY11