relational database มีโมเดลที่แตกต่างจาก code ส่วนใหญ่อย่างมาก และโดยทั่วไปแล้วนี่คือสาเหตุของความเจ็บปวดมากมาย ที่เรียกว่า "impedance mismatch" ระหว่าง object กับ database
data model ที่พัฒนาโดยใช้หลักการ functional programming มักจะเข้ากันได้ดีกว่ากับ relational database ส่วนใหญ่เป็นเพราะโมเดลแบบ functional ไม่ผสมข้อมูลกับพฤติกรรมเข้าด้วยกัน ดังนั้นการบันทึกและดึงเรคอร์ดจึงตรงไปตรงมามากกว่า อย่างไรก็ตาม เรายังต้องจัดการกับปัญหาบางอย่างอยู่ดี มาดูกันว่าโมเดล relational database เทียบกับโมเดลแบบ functional ได้อย่างไร
ก่อนอื่น ข่าวดีคือตารางใน relational database สอดคล้องกับ collection ของเรคอร์ดในโมเดลแบบ functional ได้เป็นอย่างดี และ operation แบบ set-oriented ( SELECT , WHERE ) ใน database ก็คล้ายกับ operation แบบ list-oriented ( map , filter ) ในภาษา functional
ดังนั้นกลยุทธ์ของเราคือใช้เทคนิคการ serialization จากบทที่แล้วเพื่อออกแบบ record type ที่สามารถแมปตรงไปยังตารางได้ ตัวอย่างเช่น สมมติว่าเรามี domain type แบบนี้
| | type CustomerId = CustomerId of int |
| | type String50 = String50 of string |
| | type Birthdate = Birthdate of DateTime |
| | |
| | |
| | type Customer = { |
| | CustomerId : CustomerId |
| | Name : String50 |
| | Birthdate : Birthdate option |
| | } |
แล้ว table design ที่สอดคล้องกันก็ตรงไปตรงมา
| | CREATE TABLE Customer ( |
| | CustomerId int NOT NULL , |
| | Name NVARCHAR (50) NOT NULL , |
| | Birthdate DATETIME NULL , |
| | CONSTRAINT PK_Customer PRIMARY KEY (CustomerId) |
| | ) |
ข่าวร้ายคือ relational database เก็บได้แค่ primitive เช่น strings หรือ ints ซึ่งหมายความว่าเราต้องแกะ domain type ดีๆ ของเราออก เช่น ProductCode หรือ OrderId
แย่กว่านั้นคือตารางเชิงสัมพันธ์ไม่ map เข้ากับ choice types ได้อย่างสวยงาม นี่คือสิ่งที่เราต้องดูกันในรายละเอียดเพิ่มเติม
Mapping Choice Types to Tables (การแมป Choice Type ไปยังตาราง)
เราควรโมเดล choice types ใน relational database อย่างไร? ถ้าเรามอง choice types เป็น inheritance hierarchy ระดับเดียว เราก็สามารถยืมแนวทางบางส่วนที่ใช้ map object hierarchy ไปยังโมเดลเชิงสัมพันธ์มาใช้ได้ [38]
สองแนวทางที่มีประโยชน์ที่สุดสำหรับการแมป choice types คือ
- ทุกเคสอยู่ในตารางเดียวกัน
- แต่ละเคสมีตารางของตัวเอง
ตัวอย่างเช่น สมมติว่าเรามี type อย่าง Contact (ด้านล่าง) ซึ่งมี choice type อยู่ข้างใน และเราต้องการเก็บมันไว้ใน database
| | type Contact = { |
| | ContactId : ContactId |
| | Info : ContactInfo |
| | } |
| | |
| | and ContactInfo = |
| | | Email of EmailAddress |
| | | Phone of PhoneNumber |
| | |
| | and EmailAddress = EmailAddress of string |
| | and PhoneNumber = PhoneNumber of string |
| | and ContactId = ContactId of int |
แนวทางแรก ("ทุกเคสอยู่ในตารางเดียว") คล้ายกับแนวทางที่ discussed เราจะใช้แค่ตารางเดียวเพื่อเก็บข้อมูลจากทุกเคส ซึ่งหมายความว่า (a) เราจะต้องมีแฟล็กหรือหลายแฟล็กเพื่อระบุว่าเคสไหนกำลังถูกใช้ และ (b) จะต้องมีคอลัมน์ที่เป็น NULLable ที่ใช้แค่กับบางเคสเท่านั้น
| | CREATE TABLE ContactInfo ( |
| | -- shared data |
| | ContactId int NOT NULL , |
| | -- case flags |
| | IsEmail bit NOT NULL , |
| | IsPhone bit NOT NULL , |
| | -- data for the "Email" case |
| | EmailAddress NVARCHAR (100), -- Nullable |
| | -- data for the "Phone" case |
| | PhoneNumber NVARCHAR (25), -- Nullable |
| | -- primary key constraint |
| | CONSTRAINT PK_ContactInfo PRIMARY KEY (ContactId) |
| | ) |
เราใช้แฟล็กชนิด bit สำหรับแต่ละเคสแทนที่จะใช้ฟิลด์ Tag VARCHAR ตัวเดียว เพราะมันกะทัดรัดกว่าเล็กน้อยและทำ index ได้ง่ายกว่า
แนวทางที่สอง (ที่แต่ละเคสมีตารางของตัวเอง) หมายความว่าเราสร้างตารางลูกสองตารางเพิ่มจากตารางหลัก ตารางลูกหนึ่งตารางต่อหนึ่งเคส ทุกตารางใช้ primary key เดียวกัน ตารางหลักเก็บ ID และแฟล็กบางตัวเพื่อระบุว่าเคสไหนกำลังใช้งานอยู่ ในขณะที่ตารางลูกเก็บข้อมูลของแต่ละเคส แลกกับความซับซ้อนที่เพิ่มขึ้น เราจะได้ constraint ที่ดีกว่าใน database (เช่นคอลัมน์ NOT NULL ในตารางลูก)
| | -- Main table |
| | CREATE TABLE ContactInfo ( |
| | -- shared data |
| | ContactId int NOT NULL , |
| | -- case flags |
| | IsEmail bit NOT NULL , |
| | IsPhone bit NOT NULL , |
| | CONSTRAINT PK_ContactInfo PRIMARY KEY (ContactId) |
| | ) |
| | |
| | -- Child table for "Email" case |
| | CREATE TABLE ContactEmail ( |
| | ContactId int NOT NULL , |
| | -- case-specific data |
| | EmailAddress NVARCHAR (100) NOT NULL , |
| | CONSTRAINT PK_ContactEmail PRIMARY KEY (ContactId) |
| | ) |
| | |
| | -- Child table for "Phone" case |
| | CREATE TABLE ContactPhone ( |
| | ContactId int NOT NULL , |
| | -- case-specific data |
| | PhoneNumber NVARCHAR (25) NOT NULL , |
| | CONSTRAINT PK_ContactPhone PRIMARY KEY (ContactId) |
| | ) |
แนวทาง "multitable" นี้อาจจะดีกว่าเมื่อข้อมูลที่เกี่ยวข้องกับแต่ละเคสมีขนาดใหญ่มากและมีความเหมือนกันน้อย แต่ไม่เช่นนั้นเราจะใช้แนวทางแรก "one-table" เป็นค่าเริ่มต้น
Mapping Nested Types to Tables (การแมป Nested Type ไปยังตาราง)
แล้วถ้า type หนึ่งมี type อื่นอยู่ข้างในล่ะ? เราควรจัดการแบบไหน? คำแนะนำทั่วไปคือแบบนี้
-
ถ้า inner type เป็น DDD Entity ที่มี identity ของตัวเอง ควรเก็บไว้ในตารางแยกต่างหาก
-
ถ้า inner type เป็น DDD Value Object ที่ไม่มี identity ของตัวเอง ควรเก็บแบบ "inline" ไปกับข้อมูลของตัวหลัก
ตัวอย่างเช่น type Order ของเรามี list ของค่า OrderLine type OrderLine เป็น Entity ดังนั้นมันควรถูกเก็บไว้ในตารางของตัวเอง พร้อมพอยน์เตอร์ (foreign key) ไปยัง object แม่
| | CREATE TABLE Order ( |
| | OrderId int NOT NULL , |
| | -- and other columns |
| | ) |
| | |
| | CREATE TABLE OrderLine ( |
| | OrderLineId int NOT NULL , |
| | OrderId int NOT NULL , |
| | -- and other columns |
| | ) |
ในทางกลับกัน type Order มีค่า Address อยู่สองตัว ซึ่งเป็น Value Objects ดังนั้นตาราง Order ที่สอดคล้องกันควรรวมคอลัมน์ Address ทั้งหมดไว้โดยตรง
| | CREATE TABLE Order ( |
| | OrderId int NOT NULL , |
| | |
| | -- inline the shipping address Value Object |
| | ShippingAddress1 varchar (50) |
| | ShippingAddress2 varchar (50) |
| | ShippingAddressCity varchar (50) |
| | -- and so on |
| | |
| | -- inline the billing address Value Object |
| | BillingAddress1 varchar (50) |
| | BillingAddress2 varchar (50) |
| | BillingAddressCity varchar (50) |
| | -- and so on |
| | |
| | -- other columns |
| | ) |
Reading from a Relational Database (การอ่านข้อมูลจากฐานข้อมูลเชิงสัมพันธ์)
ใน F# เรามักไม่ใช้ object-relational mapper (ORM) แต่จะทำงานโดยตรงกับ SQL commands ดิบแทน วิธีที่สะดวกที่สุดในการทำแบบนี้คือใช้ F# SQL type provider ซึ่งมีให้เลือกใช้อยู่หลายตัว สำหรับตัวอย่างนี้ เราจะใช้ type provider ที่ชื่อ FSharp.Data.SqlClient [39]
สิ่งที่พิเศษเกี่ยวกับการใช้ type provider แทนที่จะใช้ runtime library ทั่วไปคือ SQL type provider จะสร้าง type ที่ตรงกับ SQL queries หรือ SQL commands ตั้งแต่ตอน compile ถ้า SQL query ผิด คุณจะได้รับ compile time error ไม่ใช่ runtime error และถ้า SQL ถูกต้อง มันจะสร้าง F# record type ที่ตรงกับ output ของ code SQL นั้นเป๊ะๆ
สมมติว่าเราต้องการอ่าน Customer ตัวเดียวโดยใช้ CustomerId นี่คือวิธีที่ทำได้โดยใช้ type provider
ก่อนอื่นเรานิยาม connection string ที่จะใช้ตอน compile time ซึ่งโดยทั่วไปจะอ้างอิงถึง database local
| | open FSharp.Data |
| | |
| | [< Literal>] |
| | let CompileTimeConnectionString = |
| | @ "Data Source=(localdb) \ MsSqlLocalDb; Initial Catalog=DomainModelingExample;" |
จากนั้นเรานิยาม query ของเราเป็น type ที่ชื่อ ReadOneCustomer แบบนี้
| | type ReadOneCustomer = SqlCommandProvider< """ |
| | SELECT CustomerId, Name, Birthdate |
| | FROM Customer |
| | WHERE CustomerId = @customerId |
| | """ , CompileTimeConnectionString> |
ตอน compile time type provider จะรัน query นี้บน database local และสร้าง type ขึ้นมาแทนมัน ซึ่งคล้ายกับ utility อย่าง SqlMetal [40] หรือ EdmGenerator [41] ยกเว้นว่าไม่มีการสร้างไฟล์แยกออกมา type จะถูกสร้างขึ้นในที่เดิม ต่อมาเมื่อเราใช้ type นี้ เราจะให้ connection "production" อีกตัวที่ต่างจากตอน compile time
ต่อไป เช่นเดียวกับที่เราทำในตัวอย่างการ serialization ในบทที่แล้ว เราควรสร้าง function toDomain ตัวนี้จะ validate ฟิลด์ต่างๆ ใน database แล้วประกอบมันเข้าด้วยกันโดยใช้ expression แบบ result
นั่นคือ เราจะปฏิบัติต่อ database เหมือนเป็นแหล่งข้อมูลที่ไม่น่าเชื่อถือ ที่ต้อง validate เหมือนแหล่งข้อมูลอื่นๆ ดังนั้น function toDomain จะต้องคืนค่า Result<Customer,_> แทนที่จะเป็น Customer ธรรมดา นี่คือ code
| | let toDomain (dbRecord:ReadOneCustomer.Record) : Result<Customer,_> = |
| | result { |
| | let ! customerId = |
| | dbRecord.CustomerId |
| | |> CustomerId.create |
| | let ! name = |
| | dbRecord.Name |
| | |> String50.create "Name" |
| | let ! birthdate = |
| | dbRecord.Birthdate |
| | |> Result.bindOption Birthdate.create |
| | let customer = { |
| | CustomerId = customerId |
| | Name = name |
| | Birthdate = birthdate |
| | } |
| | return customer |
| | } |
เราเคยเห็น code แบบนี้มาแล้วในบท Chapter 11, Serialization แต่มีสิ่งใหม่เพิ่มเข้ามาหนึ่งอย่าง คอลัมน์ Birthdate ใน database เป็นแบบ nullable ดังนั้น type provider จึงทำให้ฟิลด์ dbRecord.Birthdate เป็น type Option แต่ function Birthdate.create ไม่รับ option เพื่อแก้ปัญหานี้ เราจะสร้าง function ช่วยเล็กๆ ที่ชื่อ bindOption ที่ช่วยให้ function แบบ "switch" ทำงานกับ option ได้
| | let bindOption f xOpt = |
| | match xOpt with |
| | | Some x -> f x |> Result.map Some |
| | | None -> Ok None |
การเขียน function toDomain แบบกำหนดเองแบบนี้และทำงานกับ Results ทั้งหมดนั้นซับซ้อนอยู่บ้าง แต่เมื่อเขียนเสร็จแล้ว เราก็มั่นใจได้ว่าจะไม่มี error ที่ไม่ถูกจัดการหลงเหลืออยู่
ในทางกลับกัน ถ้าเรามั่นใจมากว่า database จะไม่มีข้อมูลเสียหายเลย และเราเต็มใจที่จะ panic ถ้ามันเกิดขึ้น เราก็สามารถ throw exception สำหรับข้อมูลที่ไม่ถูกต้องแทนได้ ในกรณีนั้น เราสามารถเปลี่ยน code ให้ใช้ function ช่วย panicOnError (ที่แปลง error Results ให้เป็น exception) ซึ่งหมายความว่า output ของ function toDomain จะเป็น Customer ธรรมดาโดยไม่ถูกห่อด้วย Result code จะมีหน้าตาแบบนี้
| | let toDomain (dbRecord:ReadOneCustomer.Record) : Customer = |
| | |
| | let customerId = |
| | dbRecord.CustomerId |
| | |> CustomerId.create |
| | |> panicOnError "CustomerId" |
| | |
| | let name = |
| | dbRecord.Name |
| | |> String50.create "Name" |
| | |> panicOnError "Name" |
| | |
| | let birthdate = |
| | dbRecord.Birthdate |
| | |> Result.bindOption Birthdate.create |
| | |> panicOnError "Birthdate" |
| | |
| | // return the customer |
| | {CustomerId = customerId; Name = name; Birthdate = birthdate} |
โดย function ช่วย panicOnError มีหน้าตาประมาณนี้
| | exception DatabaseError of string |
| | |
| | let panicOnError columnName result = |
| | match result with |
| | | Ok x -> x |
| | | Error err -> |
| | let msg = sprintf "%s: %A" columnName err |
| | raise (DatabaseError msg) |
ไม่ว่าจะทางไหน เมื่อเรามี function toDomain แล้ว ตอนนี้เราก็เขียน code ที่อ่าน database และคืนผลลัพธ์เป็น domain type ได้แล้ว ตัวอย่างเช่น นี่คือ function readOneCustomer ที่รัน query ReadOneCustomer แล้วแปลงมันเป็น domain type
| | type DbReadError = |
| | | InvalidRecord of string |
| | | MissingRecord of string |
| | |
| | let readOneCustomer (productionConnection:SqlConnection) (CustomerId customerId) = |
| | // create the command by instantiating the type we defined earlier |
| | use cmd = new ReadOneCustomer(productionConnection) |
| | |
| | // execute the command |
| | let records = cmd.Execute(customerId = customerId) |> Seq.toList |
| | |
| | // handle the possible cases |
| | match records with |
| | // none found |
| | | [] -> |
| | let msg = sprintf "Not found. CustomerId=%A" customerId |
| | Error (MissingRecord msg) // return a Result |
| | |
| | // exactly one found |
| | | [dbCustomer] -> |
| | dbCustomer |
| | |> toDomain |
| | |> Result.mapError InvalidRecord |
| | |
| | // more than one found? |
| | | _ -> |
| | let msg = sprintf "Multiple records found for CustomerId=%A" customerId |
| | raise (DatabaseError msg) |
ก่อนอื่น สังเกตว่าตอนนี้เรากำลังส่ง SqlConnection เข้ามาโดยตรงเพื่อใช้เป็น connection "production"
ต่อไป เรามีสามกรณีที่เป็นไปได้ที่ต้องจัดการ คือไม่พบเรคอร์ด, พบเรคอร์ดเดียวพอดี, และพบเรคอร์ดมากกว่าหนึ่ง เราต้องตัดสินใจว่ากรณีไหนควรจัดการเป็นส่วนหนึ่งของ domain และกรณีไหนไม่ควรเกิดขึ้นเลย (และสามารถจัดการด้วยการ panic ได้) ในกรณีนี้ เราจะบอกว่าการไม่พบเรคอร์ดเป็นไปได้และจะถูกจัดการเป็น Result.Error ในขณะที่การพบมากกว่าหนึ่งเรคอร์ดจะถูกจัดการด้วยการ panic
การจัดการกรณีต่างๆ เหล่านี้ดูเหมือนจะเป็นงานเยอะ แต่ประโยชน์คือคุณกำลังตัดสินใจอย่างชัดเจนเกี่ยวกับ error ที่เป็นไปได้ (และมันถูกบันทึกไว้ใน code) แทนที่จะสมมติว่าทุกอย่างทำงานได้และเจอ NullReferenceException ที่ไหนสักแห่งในภายหลัง
และแน่นอนว่า เราสามารถทำให้ code นี้สะอาดขึ้นได้โดยทำตามหลักการ "parameterize all the things" เพื่อสร้าง function ทั่วไป สมมติชื่อ convertSingleDbRecord โดยที่ชื่อตาราง, ID, เรคอร์ด และตัวแปลง toDomain ทั้งหมดถูกส่งเข้ามาเป็นพารามิเตอร์
| | let convertSingleDbRecord tableName idValue records toDomain = |
| | match records with |
| | // none found |
| | | [] -> |
| | let msg = sprintf "Not found. Table=%s Id=%A" tableName idValue |
| | Error msg // return a Result |
| | |
| | // exactly one found |
| | | [dbRecord] -> |
| | dbRecord |
| | |> toDomain |
| | |> Ok // return a Result |
| | |
| | // more than one found? |
| | | _ -> |
| | let msg = sprintf "Multiple records found. Table=%s Id=%A" tableName idValue |
| | raise (DatabaseError msg) |
ด้วย generic function ตัวนี้ code สามารถลดลงเหลือแค่ไม่กี่บรรทัด
| | let readOneCustomer (productionConnection:SqlConnection) (CustomerId customerId) = |
| | use cmd = new ReadOneCustomer(productionConnection) |
| | let tableName = "Customer" |
| | |
| | let records = cmd.Execute(customerId = customerId) |> Seq.toList |
| | convertSingleDbRecord tableName customerId records toDomain |
Reading Choice Types from a Relational Database (การอ่าน Choice Type จากฐานข้อมูลเชิงสัมพันธ์)
เราสามารถอ่าน choice types ได้ด้วยวิธีเดียวกัน แม้จะซับซ้อนกว่าเล็กน้อย สมมติว่าเราใช้แนวทาง one-table เพื่อเก็บเรคอร์ด ContactInfo และเราต้องการอ่าน ContactInfo ตัวเดียวโดยใช้ ContactId เช่นเดียวกับก่อนหน้านี้ เรานิยาม query ของเราเป็น type แบบนี้
| | type ReadOneContact = SqlCommandProvider< """ |
| | SELECT ContactId,IsEmail,IsPhone,EmailAddress,PhoneNumber |
| | FROM ContactInfo |
| | WHERE ContactId = @contactId |
| | """ , CompileTimeConnectionString> |
ต่อไป เราสร้าง function toDomain ตัวนี้จะตรวจสอบแฟล็กใน database ( IsEmail ) เพื่อดูว่าจะสร้าง ContactInfo เคสไหน แล้วประกอบข้อมูลของแต่ละเคสโดยใช้ child result expression (ดีใจกับความ composable นี้จัง!)
| | let toDomain (dbRecord:ReadOneContact.Record) : Result<Contact,_> = |
| | result { |
| | let ! contactId = |
| | dbRecord.ContactId |
| | |> ContactId.create |
| | |
| | let ! contactInfo = |
| | if dbRecord.IsEmail then |
| | result { |
| | // get the primitive string which should not be NULL |
| | let ! emailAddressString = |
| | dbRecord.EmailAddress |
| | |> Result.ofOption "Email expected to be non null" |
| | // create the EmailAddress simple type |
| | let ! emailAddress = |
| | emailAddressString |> EmailAddress.create |
| | // lift to the Email case of Contact Info |
| | return (Email emailAddress) |
| | } |
| | else |
| | result { |
| | // get the primitive string which should not be NULL |
| | let ! phoneNumberString = |
| | dbRecord.PhoneNumber |
| | |> Result.ofOption "PhoneNumber expected to be non null" |
| | // create the PhoneNumber simple type |
| | let ! phoneNumber = |
| | phoneNumberString |> PhoneNumber.create |
| | // lift to the PhoneNumber case of Contact Info |
| | return (Phone phoneNumber) |
| | } |
| | |
| | let contact = { |
| | ContactId = contactId |
| | Info = contactInfo |
| | } |
| | return contact |
| | } |
คุณจะเห็นได้ว่าในเคส Email ตัวอย่างเช่น คอลัมน์ EmailAddress ใน database เป็นแบบ nullable ดังนั้น dbRecord.EmailAddress ที่ type provider สร้างขึ้นจึงเป็น type Option ดังนั้นก่อนอื่นเราต้องใช้ Result.ofOption เพื่อแปลง Option เป็น Result (เผื่อกรณีที่มันหายไป) จากนั้นสร้าง type EmailAddress แล้ว lift มันขึ้นไปเป็นเคส Email ของ ContactInfo
มันซับซ้อนยิ่งกว่าตัวอย่าง Customer ก่อนหน้านี้อีก แต่เราก็มั่นใจมากอีกครั้งว่าเราจะไม่เจอ error ที่ไม่คาดคิด
อ้อ ถ้าคุณสงสัยว่า code ของ function Result.ofOption หน้าตาเป็นอย่างไร นี่คือมัน
| | module Result = |
| | /// Convert an Option into a Result |
| | let ofOption errorValue opt = |
| | match opt with |
| | | Some v -> Ok v |
| | | None -> Error errorValue |
เช่นเดียวกับก่อนหน้านี้ เมื่อเรามี function toDomain แล้ว เราสามารถใช้มันร่วมกับ function ช่วย convertSingleDbRecord ที่เราสร้างไว้ก่อนหน้านี้
| | let readOneContact (productionConnection:SqlConnection) (ContactId contactId) = |
| | use cmd = new ReadOneContact(productionConnection) |
| | let tableName = "ContactInfo" |
| | |
| | let records = cmd.Execute(contactId = contactId) |> Seq.toList |
| | convertSingleDbRecord tableName contactId records toDomain |
คุณจะเห็นว่าการสร้าง function toDomain คือส่วนที่ยากที่สุด เมื่อทำเสร็จแล้ว code สำหรับเข้าถึง database จริงๆ ก็ค่อนข้างง่าย
คุณอาจกำลังคิดว่า นี่มันงานเยอะขนาดนี้เลยเหรอ? เราใช้อะไรอย่าง Entity Framework หรือ NHibernate ที่ทำการแมปทั้งหมดนี้ให้อัตโนมัติไม่ได้เหรอ? คำตอบคือไม่ได้ ถ้าคุณต้องการรักษา integrity ของ domain เอาไว้ ORM อย่างที่กล่าวมาไม่สามารถ validate ที่อยู่อีเมลและจำนวนคำสั่งซื้อ จัดการกับ choice types ที่ซ้อนกัน และอื่นๆ ได้ ใช่ว่ามันน่าเบื่อที่ต้องเขียน code database แบบนี้ แต่กระบวนการนี้เป็นกลไกที่ตรงไปตรงมา และไม่ใช่ส่วนที่ยากที่สุดของการเขียนแอปพลิเคชันเลย!
Writing to a Relational Database (การเขียนข้อมูลลงฐานข้อมูลเชิงสัมพันธ์)
การเขียนลง relational database เป็นไปตามรูปแบบเดียวกับการอ่าน คือเราแปลง domain object ของเราเป็น DTO แล้วรัน insert หรือ update command
วิธีที่ง่ายที่สุดในการทำ database insert คือให้ SQL type provider สร้าง mutable type ที่แทนโครงสร้างของตาราง แล้วเราก็แค่ set ฟิลด์ของ type นั้น
นี่คือการสาธิต ก่อนอื่น เราใช้ type provider เพื่อตั้งค่า type สำหรับทุกตาราง
| | type Db = SqlProgrammabilityProvider<CompileTimeConnectionString> |
และตอนนี้เราสามารถนิยาม function writeContact ที่รับ Contact และ set ฟิลด์ทั้งหมดใน Contact ที่สอดคล้องกันจาก database
| | let writeContact (productionConnection:SqlConnection) (contact:Contact) = |
| | |
| | // extract the primitive data from the domain object |
| | let contactId = contact.ContactId |> ContactId.value |
| | let isEmail,isPhone,emailAddressOpt,phoneNumberOpt = |
| | match contact.Info with |
| | | Email emailAddress-> |
| | let emailAddressString = emailAddress |> EmailAddress.value |
| | true,false,Some emailAddressString,None |
| | | Phone phoneNumber -> |
| | let phoneNumberString = phoneNumber |> PhoneNumber.value |
| | false,true,None,Some phoneNumberString |
| | |
| | // create a new row |
| | let contactInfoTable = new Db.dbo.Tables.ContactInfo() |
| | let newRow = contactInfoTable.NewRow() |
| | newRow.ContactId <- contactId |
| | newRow.IsEmail <- isEmail |
| | newRow.IsPhone <- isPhone |
| | // use optional types to map to NULL in the database |
| | newRow.EmailAddress <- emailAddressOpt |
| | newRow.PhoneNumber <- phoneNumberOpt |
| | |
| | // add to table |
| | contactInfoTable.Rows.Add newRow |
| | |
| | // push changes to the database |
| | let recordsAffected = contactInfoTable.Update(productionConnection) |
| | recordsAffected |
อีกแนวทางหนึ่งที่ควบคุมได้มากกว่าคือใช้คำสั่ง SQL ที่เขียนเอง ตัวอย่างเช่น เพื่อ insert Contact ใหม่ ก่อนอื่นเรานิยาม type ที่แทนคำสั่ง SQL INSERT
| | type InsertContact = SqlCommandProvider< """ |
| | INSERT INTO ContactInfo |
| | VALUES (@ContactId,@IsEmail,@IsPhone,@EmailAddress,@PhoneNumber) |
| | """ , CompileTimeConnectionString> |
และตอนนี้เราสามารถนิยาม function writeContact ที่รับ Contact ดึง primitive ออกมาจาก choice type แล้วรัน command
| | let writeContact (productionConnection:SqlConnection) (contact:Contact) = |
| | |
| | // extract the primitive data from the domain object |
| | let contactId = contact.ContactId |> ContactId.value |
| | let isEmail,isPhone,emailAddress,phoneNumber = |
| | match contact.Info with |
| | | Email emailAddress-> |
| | let emailAddressString = emailAddress |> EmailAddress.value |
| | true,false,emailAddressString, null |
| | | Phone phoneNumber -> |
| | let phoneNumberString = phoneNumber |> PhoneNumber.value |
| | false,true, null ,phoneNumberString |
| | |
| | // write to the DB |
| | use cmd = new InsertContact(productionConnection) |
| | cmd.Execute(contactId,isEmail,isPhone,emailAddress,phoneNumber) |