Đăng ký để xem nội dung này
Tạo tài khoản miễn phí và đăng ký gói học để truy cập toàn bộ bài học, video và tài liệu độc quyền.
Đăng ký ngay — Miễn phí Đã có tài khoản? Đăng nhậpThêm dữ liệu mới vào cơ sở dữ liệu với LINQ
🧠 BÀI GIẢNG: THÊM MỚI DỮ LIỆU BẰNG ENTITY FRAMEWORK (.NET 8 MVC)
🧩 1. Tạo hàm lưu trong class KhoaHocService
Tạo class service để xử lý nghiệp vụ:
// Services/KhoaHocService.cs
using MyProject.Models.Entity;
namespace MyProject.Services
{
public class KhoaHocService
{
private readonly WebDaoTaoContext _context;
public KhoaHocService(AppDbContext context)
{
_context = context;
}
// ✅ Hàm lưu mới dữ liệu
public bool ThemMoi(KhoaHoc model)
{
try
{
_context.KhoaHoc.Add(model);
_context.SaveChanges();
return true;
}
catch (Exception ex)
{
// Có thể log lỗi ra file hoặc hệ thống
Console.WriteLine("Lỗi lưu KhoaHoc: " + ex.Message);
return false;
}
}
}
}
👉 Giải thích:
-
_context.KhoaHoc.Add(model)thêm bản ghi mới vào context. -
SaveChanges()ghi thay đổi xuống database. -
Trả về
true/falsegiúp Controller biết có lưu thành công hay không.
🧭 2. Tạo Controller: KhoaHocController
// Controllers/KhoaHocController.cs
using Microsoft.AspNetCore.Mvc;
using MyProject.Models.Entity;
using MyProject.Services;
namespace MyProject.Controllers
{
public class KhoaHocController : Controller
{
private readonly KhoaHocService _service;
public KhoaHocController(KhoaHocService service)
{
_service = service;
}
// ✅ Hiển thị form thêm mới
[HttpGet]
public IActionResult ThemMoi()
{
return View();
}
// ✅ Action nhận dữ liệu submit từ form
[HttpPost]
public IActionResult LuuThemMoi(KhoaHoc model)
{
if (ModelState.IsValid)
{
bool result = _service.ThemMoi(model);
if (result)
{
TempData["Success"] = "Thêm mới khóa học thành công!";
return RedirectToAction("DanhSach");
}
else
{
TempData["Error"] = "Có lỗi xảy ra khi lưu dữ liệu.";
}
}
// Nếu model không hợp lệ hoặc lưu lỗi, quay lại form
return View(model);
}
// ✅ Trang danh sách (để chuyển hướng sau khi thêm)
public IActionResult DanhSach()
{
// Demo: tạm chưa lấy dữ liệu
return View();
}
}
}
👉 Lưu ý đặt tên form:
-
Action
[HttpPost]có cùng tên với[HttpGet](ThemMoi) → MVC sẽ mapping dữ liệu submit tự động thông qua tên thuộc tính (name) trong form.
🧾 3. Tạo View thêm mới (ThemMoi.cshtml)
Đặt tại:
Views/KhoaHoc/ThemMoi.cshtml
@model MyProject.Models.Entity.KhoaHoc
@{
ViewData["Title"] = "Thêm mới khóa học";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<div class="container mt-4">
<h3>@ViewData["Title"]</h3>
<hr />
@if (TempData["Error"] != null)
{
<div class="alert alert-danger">@TempData["Error"]</div>
}
@using (Html.BeginForm("LuuThemMoi", "KhoaHoc", FormMethod.Post))
{
<div class="form-group mb-3">
<label for="TenKhoaHoc">Tên khóa học</label>
@Html.TextBoxFor(m => m.TenKhoaHoc, new { @class = "form-control", placeholder = "Nhập tên khóa học" })
</div>
<div class="form-group mb-3">
<label for="MoTa">Mô tả</label>
@Html.TextAreaFor(m => m.MoTa, new { @class = "form-control", rows = "4", placeholder = "Nhập mô tả khóa học" })
</div>
<div class="form-group mb-3">
<button type="submit" class="btn btn-primary">
<i class="bi bi-save"></i> Lưu lại
</button>
<a href="@Url.Action("DanhSach", "KhoaHoc")" class="btn btn-secondary">Hủy</a>
</div>
}
</div>
👉 Giải thích:
-
Html.BeginForm("ThemMoi", "KhoaHoc", FormMethod.Post)→ gửi dữ liệu đếnKhoaHocController.ThemMoi([HttpPost]). -
@Html.TextBoxForvà@Html.TextAreaFortự động bind dữ liệu vào modelKhoaHoc. -
Có nút Lưu và Hủy.
⚙️ Cấu hình khởi tạo service (Dependency Injection)
Thêm vào Program.cs:
builder.Services.AddScoped<KhoaHocService>();
✅ Kết quả chạy thử:
-
Vào link
/KhoaHoc/ThemMoi→ form hiện ra. -
Nhập tên + mô tả → bấm Lưu lại.
-
Controller nhận
model, gọiservice.ThemMoi(model)→ thêm vào DB. -
Chuyển hướng sang trang danh sách hoặc hiển thị thông báo thành công.
Bài tập số 16: Thêm dữ liệu mới vào cơ sở dữ liệu với LINQ
Yêu cầu:
-
QuanLyDaoTaoDB
-
Thực hành lại nội dung đã học.
-
Làm tương tự với bảng NhanVien, HocVien
Nộp bài:
-
Nén project đã làm và nộp file.