ตัวอย่างนี้จะแสดงวิธีใช้งาน Entity Framework Core เบื้องต้นประกอบด้วยการสร้าง Context, Insert และ Query ข้อมูล Student ในฐานข้อมูล PostgreSQL
สามารถโหลดตัวอย่างได้ตามลิงก์นี้ HelloEf
สร้างโปรเจคและติดตั้ง Package
dotnet new console --language F# --output src/HelloEfdotnet add src/HelloEf package Npgsql.EntityFrameworkCore.PostgreSQL
dotnet add src/HelloEf package \
Microsoft.Extensions.DependencyInjection
ประกาศ Model และ Context (Models.fs)
- ประกาศ Model
Student
ด้วย Record และใช้ CLIMutableAttribute เพื่อให้ Compiler สร้าง Constructor และ Setter, getter ให้ทุกฟิลด์ในStudent
โดยกำหนดให้Id
เป็น Primary key
namespace HelloEf.Modelsopen System
open Microsoft.EntityFrameworkCore
open System.ComponentModel.DataAnnotations[<CLIMutable>]
type Student =
{ [<Key>]
Id: int
Name: string
Gpa: float }
- สร้าง Context ชื่อ
MyContext
ที่มี DbSet เดียว คือStudents
type MyContext(options: DbContextOptions) =
inherit DbContext(options) [<DefaultValue>]
val mutable private students: DbSet<Student> member this.Students
with get() = this.students
and set v = this.students <- v
สร้าง Instance ของ MyContext จาก Connection string (Program.fs)
- สร้าง Instance ของ MyContext ผ่าน ServiceCollection และ ServiceProvider ใน package Microsoft.Extensions.DependencyInjection โดย Register MyContext ด้วยฟังก์ชัน AddDbContext
- มีการใช้ ConsoleLogProvider ใน package Microsoft.Extension.Logging.Console เพื่อให้โปรแกรมเขียน Log SQL ทุกครั้งที่มีการทำงานกับฐานข้อมูล
open Microsoft.EntityFrameworkCore
open Microsoft.Extensions.Logging.Console
open Microsoft.Extensions.Logging
open Microsoft.Extensions.DependencyInjectionlet createContext (connectionString: string) =
let collection =
ServiceCollection()
.AddDbContext<MyContext>(fun options ->
let provider =
new ConsoleLoggerProvider((fun _ level ->
level <> LogLevel.Debug), true)
let factory = new LoggerFactory([provider])
options.UseLoggerFactory(factory) |> ignore
options.UseNpgsql connectionString |> ignore
)
let provider = collection.BuildServiceProvider()
provider.GetService<MyContext>()let connectionString = "Host=localhost;User Id=postgres;Password=1234;Database=MyDB"use context = createContext connectionString
Insert ข้อมูลด้วยฟังก์ชัน AddRange (Program.fs)
- การ Insert ข้อมูลทำเหมือน C# ต่างกันที่ใช้ Record แทน Class
let insertStudents (context: MyContext) students =
context.Students.AddRange students |> ignore
context.SaveChanges()let students = [|
{ Id = 0; Name = "A"; Gpa = 3.5 }
{ Id = 0; Name = "B"; Gpa = 2.0 }
{ Id = 0; Name = "C"; Gpa = 3.8 }
|]insertStudents context students |> ignore
Query ข้อมูลด้วย Query Expression (Program.fs)
- ใน F# จะใช้ Query Expression ที่มี Syntax คล้ายกับ LINQ Query ในการดึงข้อมูลจากฐานข้อมูล
let findStudentsByGpa (context: MyContext) gpa =
query {
for student in context.Students do
where (student.Gpa >= gpa)
select student
}let clevers = findStudentsByGpa context 3.5for student in clevers do
printfn "Name = %s, Gpa = %.2f" student.Name student.Gpa
รันโปรแกรมด้วยคำสั่ง
dotnet run --project src/HelloEf/HelloEf.fsproj
จะได้ Log SQL และ Output ดังนี้