Entity Framework Core (PostgreSQL)
การใช้ EF Core ทำงานกับฐานข้อมูลให้ดำเนินการในแนวทาง Database First คือ
- สร้างฐานข้อมูล และตารางข้อมูล [Managing Database Schemas]
- ใช้คำสั่ง Scaffold ของ EF Core สร้าง DBContext และ Model เพื่อใช้เขียนโปรแกรมจัดการข้อมูล
การติดตั้ง
การติดตั้ง EF Core เพื่อใช้งานกับฐานข้อมูล PostgreSQL จะต้องติดตั้ง Package โดยใช้ Package Manager Console ด้วยคำสั่งดังนี้
การใช้คำสั่ง Scaffold
- ติดตั้ง Nuget Packages ดังนี้
- Npgsql.EntityFrameworkCore.PostgreSQL
- Microsoft.EntityFrameworkCore.Tools
- เปิด Package Manager Console เพื่อรันคำสั่ง Scaffold
- รันคำสั่งดังนี้
Entity Context Dependency Injection
Database Connection Pool
การใช้งาน
Asynchronous Method
CRUD
Create
Read
Update
Scaffold
Entity Context Dependency Injection
Database Connection Pool
Asynchronous Method
CRUD
การบันทึกข้อมูล (CUD Operation)
การจัดการข้อมูลโดยใช้ Context และ Entity Classes โดยการเปลี่ยนแปลงที่เกิดขึ้นกับ Entity Classes จะถูกจัดการโดย ChangeTracker เมื่อมีการทำงานกับ Entity Classes เสร็จสิ้น ต้องเรียกใช้ context.SaveChangesAsync() ทุกครั้ง เพื่อบันทึกการเปลี่ยนแปลง โดยการทำงานของ Entity State แสดงดังตารางที่ 1 ดังนี้
ตารางที่ 1 แสดงการทำงานของ Entity State
Entity state | Tracked by context | Exists in database | Property values have been modified | Action on SaveChanges |
---|---|---|---|---|
Detached | No | - | - | - |
Added | Yes | No | - | Insert |
Unchanged | Yes | Yes | No | - |
Modified | Yes | Yes | Yes | Update |
Deleted | Yes | Yes | - | Delete |
การเพิ่มข้อมูล
ใช้ Add method โดย Entity state ก่อนถูกบันทึก จะมีสถานะ Added ดังตัวอย่างต่อไปนี้
using (var context = new ProfileContext())
{
var profile = new Profile { Name = "Dev_1 name" };
await context.Profiles.AddAsync(profile); // Profiles state : Added
await context.SaveChangesAsync();
}
การแก้ไขข้อมูล
Entity Classes เริ่มต้นดึงข้อมูลจากฐานข้อมูล มีค่า Entity state เป็น Unchanged เมื่อมีการเปลี่ยนแปลงข้อมูล ค่า Entity state เปลี่ยนเป็น Modified ดังตัวอย่างต่อไปนี้
using (var context = new ProfileContext())
{
var profile = await context.Profiles.FirstAsync(); // Profiles state : Unchanged
profile.Name = "Dev_2 name"// Profiles state : Modified
await context.SaveChangesAsync();
}
การลบข้อมูล
Entity Classes เริ่มต้นดึงข้อมูลจากฐานข้อมูล มีค่า Entity state เป็น Unchanged เมื่อมีการลบข้อมูลโดยใช้ Remove method ค่า Entity state เปลี่ยนเป็น Deleted ดังตัวอย่างต่อไปนี้
using (var context = new ProfileContext())
{
var profile = await context.Profiles.FirstAsync(); // Profiles state : Unchanged
context.Profiles.Remove(profile); // Profiles state : Deleted
await context.SaveChangesAsync();
}
Transaction
กระบวนการทำงานย้อนกลับ กรณีมีกระบวนการทำงาน CUD Operation ผิดพลาดในขั้นตอนใดขั้นตอนหนึ่ง
using (var context = new ProfileContext())
{
using (var transaction = context.Database.BeginTransaction())
{
var profile = new Profile { Name = "Dev_1 name" };
await context.Profiles.AddAsync(profile);
await context.SaveChangesAsync();
await transaction.CommitAsync();
}
}