Làm việc với Entity Framework trong C# – Phần 17
1. Giới thiệu về Entity Framework
Entity Framework (EF) là một ORM (Object-Relational Mapping) giúp làm việc với cơ sở dữ liệu dễ dàng trong C#.
🔹 Ưu điểm của Entity Framework:
✅ Giảm thiểu việc viết SQL thủ công.
✅ Làm việc với dữ liệu theo hướng đối tượng.
✅ Hỗ trợ nhiều loại cơ sở dữ liệu như SQL Server, MySQL, PostgreSQL.
🔹 Các cách sử dụng Entity Framework:
- Code First: Định nghĩa database bằng C#.
- Database First: Tạo code từ database có sẵn.
- Model First: Dùng giao diện để thiết kế model.
2. Cài đặt Entity Framework Core
👉 Thêm Entity Framework vào dự án:
dotnet add package Microsoft.EntityFrameworkCore
dotnet add package Microsoft.EntityFrameworkCore.SqlServer
dotnet add package Microsoft.EntityFrameworkCore.Tools
📌 Nếu dùng MySQL:
dotnet add package Pomelo.EntityFrameworkCore.MySql
3. Cấu hình DbContext và Model
3.1. Tạo Model (Code First)
👉 Tạo class Student.cs để làm bảng Students trong database:
public class Student
{
public int Id { get; set; }
public string Name { get; set; }
public int Age { get; set; }
}
3.2. Cấu hình DbContext
👉 Tạo AppDbContext.cs để quản lý database:
using Microsoft.EntityFrameworkCore;
public class AppDbContext : DbContext
{
public DbSet<Student> Students { get; set; }
protected override void OnConfiguring(DbContextOptionsBuilder options)
{
options.UseSqlServer("Server=localhost;Database=SchoolDB;Trusted_Connection=True;");
}
}
📌 Cấu hình kết nối với SQL Server (Server=localhost;Database=SchoolDB;Trusted_Connection=True;).
4. Tạo Database với Migration
👉 Chạy lệnh tạo database:
dotnet ef migrations add InitialCreate
dotnet ef database update
📌 Lệnh này sẽ:
- Tạo migration
InitialCreate. - Cập nhật database theo model
Student.
5. Thao tác CRUD với Entity Framework
5.1. Thêm dữ liệu (Create)
using System;
class Program
{
static void Main()
{
using var context = new AppDbContext();
var student = new Student { Name = "Nguyễn Văn A", Age = 20 };
context.Students.Add(student);
context.SaveChanges();
Console.WriteLine("✅ Thêm sinh viên thành công!");
}
}
📌 Giải thích:
context.Students.Add(student): Thêm sinh viên.context.SaveChanges(): Lưu thay đổi vào database.
5.2. Lấy dữ liệu (Read)
using System;
using System.Linq;
class Program
{
static void Main()
{
using var context = new AppDbContext();
var students = context.Students.ToList();
foreach (var student in students)
{
Console.WriteLine($"🧑🎓 ID: {student.Id}, Tên: {student.Name}, Tuổi: {student.Age}");
}
}
}
📌 Giải thích:
context.Students.ToList(): Lấy danh sách sinh viên.
5.3. Cập nhật dữ liệu (Update)
using System;
using System.Linq;
class Program
{
static void Main()
{
using var context = new AppDbContext();
var student = context.Students.FirstOrDefault(s => s.Id == 1);
if (student != null)
{
student.Age = 21;
context.SaveChanges();
Console.WriteLine("✅ Cập nhật tuổi thành công!");
}
}
}
📌 Giải thích:
FirstOrDefault(s => s.Id == 1): Lấy sinh viên cóId = 1.- Cập nhật tuổi và
SaveChanges().
5.4. Xóa dữ liệu (Delete)
using System;
using System.Linq;
class Program
{
static void Main()
{
using var context = new AppDbContext();
var student = context.Students.FirstOrDefault(s => s.Id == 1);
if (student != null)
{
context.Students.Remove(student);
context.SaveChanges();
Console.WriteLine("✅ Xóa sinh viên thành công!");
}
}
}
📌 Giải thích:
Remove(student): Xóa sinh viên khỏi database.
6. Sử dụng Entity Framework với Dependency Injection
🔹 Nếu làm việc với ASP.NET Core, ta cần cấu hình DbContext trong Program.cs:
using Microsoft.EntityFrameworkCore;
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddDbContext<AppDbContext>(options =>
options.UseSqlServer("Server=localhost;Database=SchoolDB;Trusted_Connection=True;"));
📌 Sau đó có thể inject AppDbContext vào Controller:
public class StudentController : ControllerBase
{
private readonly AppDbContext _context;
public StudentController(AppDbContext context)
{
_context = context;
}
[HttpGet]
public IActionResult GetStudents()
{
return Ok(_context.Students.ToList());
}
}
7. Tổng Kết
✅ Entity Framework giúp làm việc với database dễ dàng.
✅ Hỗ trợ Code First, Database First, Model First.
✅ Có thể dùng với SQL Server, MySQL, PostgreSQL…
📌 Các bước chính:
- Cài đặt Entity Framework.
- Tạo Model và DbContext.
- Dùng Migration để tạo database.
- Thực hiện CRUD (Create, Read, Update, Delete).
💡 Bài tiếp theo:
👉 Tạo API RESTful với ASP.NET Core – Phần 18 🚀