Xây dựng ASP.
NET 8 Web API Code First
1. Giới thiệu
Trong bài lab này, chúng ta sẽ tạo một API trong ASP.NET 8 theo mô hình Code First với Entity Framework Core. Có hai cách xây dựng cơ sở dữ liệu:
• Dùng Fluent API
• Dùng Data Annotation (không dùng Fluent API)
Bài lab sẽ tạo hai model Student và Course có mối quan hệ "nhiều - nhiều" (Many-to-Many) thông qua bảng trung gian Enrollment.
2. Tạo Dự Án ASP.NET 8 Web API
Bước 1: Tạo Project
Mở terminal hoặc command prompt và chạy lệnh sau (hoặc sử dụng VS2022 chọn WEB API template):
mkdir AspNet8CodeFirstAPI
cd AspNet8CodeFirstAPI
dotnet new webapi -n AspNet8CodeFirstAPI
cd AspNet8CodeFirstAPI
Bước 2: Cài Đặt Entity Framework Core
Cài đặt các package Entity Framework Core:
dotnet add package Microsoft.EntityFrameworkCore.SqlServer
dotnet add package Microsoft.EntityFrameworkCore.Design
3. Xây dựng Models
3.1. Không dùng Fluent API (Dùng Data Annotation)
Tạo file Models/Student.cs:
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
public class Student
{
[Key]
public int StudentId { get; set; }
[Required, MaxLength(100)]
public string Name { get; set; }
public List<Enrollment> Enrollments { get; set; } = new();
}
Tạo file Models/Course.cs:
public class Course
{
[Key]
public int CourseId { get; set; }
[Required, MaxLength(100)]
public string Title { get; set; }
public List<Enrollment> Enrollments { get; set; } = new();
}
Tạo file Models/Enrollment.cs:
public class Enrollment
{
[Key]
public int Id { get; set; }
[ForeignKey("Student")]
public int StudentId { get; set; }
public Student Student { get; set; }
[ForeignKey("Course")]
public int CourseId { get; set; }
public Course Course { get; set; }
}
3.2. Dùng Fluent API
Trong DbContext, thiết lập mối quan hệ như sau:
using Microsoft.EntityFrameworkCore;
public class SchoolContext : DbContext
{
public DbSet<Student> Students { get; set; }
public DbSet<Course> Courses { get; set; }
public DbSet<Enrollment> Enrollments { get; set; }
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<Enrollment>()
.HasOne(e => e.Student)
.WithMany(s => s.Enrollments)
.HasForeignKey(e => e.StudentId);
modelBuilder.Entity<Enrollment>()
.HasOne(e => e.Course)
.WithMany(c => c.Enrollments)
.HasForeignKey(e => e.CourseId);
}
}
4. Cấu Hình DbContext trong Program.cs
Thêm cấu hình SQL Server trong Program.cs:
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddDbContext<SchoolContext>(options =>
options.UseSqlServer("Server=.;Database=SchoolDB;Trusted_Connection=True;"));
builder.Services.AddControllers();
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();
var app = builder.Build();
app.UseSwagger();
app.UseSwaggerUI();
app.UseAuthorization();
app.MapControllers();
app.Run();
5. Tạo Migration và Database
dotnet ef migrations add InitialCreate
dotnet ef database update
6. Tạo API Controller
Tạo Controllers/StudentsController.cs:
[Route("api/[controller]")]
[ApiController]
public class StudentsController : ControllerBase
{
private readonly SchoolContext _context;
public StudentsController(SchoolContext context)
{
_context = context;
}
[HttpGet]
[Route("getstudents")]
public async Task<ActionResult<IEnumerable<Student>>> GetStudents()
{
return await _context.Students.Include(s => s.Enrollments).ThenInclude(e => e.Course).ToListAsync();
}
[HttpPost]
[Route("add")]
public async Task<ActionResult<Student>> PostStudent(Student student)
{
_context.Students.Add(student);
await _context.SaveChangesAsync();
return CreatedAtAction(nameof(GetStudents), new { id = student.StudentId }, student);
}
}
7. Chạy API và Test với Swagger
Chạy lệnh:
dotnet run
Mở trình duyệt và truy cập https://localhost:5001/swagger để kiểm tra API.
8. Note
https://learn.microsoft.com/en-us/ef/core/dbcontext-configuration/
https://www.brightertools.com/post/idesigntimedbcontextfactory-update-for-entity-framework-6-migrations-design-time-tools-net-core-6
https://www.learnentityframeworkcore.com/configuration/fluent-api