I've been looking into F# in relation to CRUD with data . and I have been using FSharp.Data.SqlClient
I can't see an easy way to update all fields from an object.
For example I want to execute the code below - and then I want to present that data to a web page. The web page will make some changes ( maybe ) - then I want to use the object to update the database.
I don't want to have to write code to map every single field. Additionally, I am still trying to get my head around how this is done in an immutable way.
let getOrders2() =
let cmd = new SqlCommandProvider<"
SELECT top 10 * from orders
" , connectionString>(connectionString)
let orders = cmd.Execute()
let o2 = orders |> Seq.toList
-
Consider using Dapper: github.com/Dzoukr/Dapper.FSharp#updateScott Hutchinson– Scott Hutchinson02/20/2021 00:33:03Commented Feb 20, 2021 at 0:33
-
@ScottHutchinson Thanks - but I think you have to define all the F# objects in Dappa? that seems a bit cumbersome if you don't have to ..Martin Thompson– Martin Thompson02/20/2021 00:59:24Commented Feb 20, 2021 at 0:59
1 Answer 1
Updating multiple fields at once from an object is straightforward:
let updateEmployee employee =
use cmd =
new SqlCommandProvider<
"update Employees set \
FirstName = @FirstName,
LastName = @LastName
where EmployeeID = @EmployeeID",
connectionString>(connectionString)
let nRows =
cmd.Execute(
employee.FirstName,
employee.LastName,
employee.EmployeeID)
assert(nRows = 1)
Writing a web app with immutable objects is a big topic. Are you using F# just on the server, or also in the client?
-
1thank you . F# on the server - expose DAL through Rest API. Vuejs on the client ( Quasar to be specific ) I wanted to avoid having to set every single field - some of my tables have quite a few fields in them. Is there an easy way to do that in this framework?Martin Thompson– Martin Thompson02/20/2021 05:04:40Commented Feb 20, 2021 at 5:04
-
You could have different update statements that set only the fields needed for each use case. Or you could write and call a general-purpose stored proc that consumes XML (or JSON) instead of executing a SQL update statement directly. It depends on how creative you want to get.Brian Berns– Brian Berns02/20/2021 05:07:46Commented Feb 20, 2021 at 5:07
-
thanks, I guess I want to only update the fields that have changed. So I would somehow need to iterate the object properties and compare them I guess..?Martin Thompson– Martin Thompson02/20/2021 21:27:35Commented Feb 20, 2021 at 21:27
-
You can do that, but in my experience it's almost always more trouble than it's worth. In a typical "CRUD" app, it's better to have a single "dirty" flag at the object level, rather than tracking at the property level. You can optimize later if necessary. Just my opinion.Brian Berns– Brian Berns02/20/2021 21:53:42Commented Feb 20, 2021 at 21:53