WEB API LAB
WEB API LAB
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:
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.
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
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
[Required, MaxLength(100)]
public string Name { get; set; }
[Required, MaxLength(100)]
public string Title { 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
using Microsoft.EntityFrameworkCore;
modelBuilder.Entity<Enrollment>()
.HasOne(e => e.Course)
.WithMany(c => c.Enrollments)
.HasForeignKey(e => e.CourseId);
}
}
4. Cấu Hình DbContext trong Program.cs
builder.Services.AddControllers();
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();
Tạo Controllers/StudentsController.cs:
[Route("api/[controller]")]
[ApiController]
public class StudentsController : ControllerBase
{
private readonly SchoolContext _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
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