1

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
Martin Thompson
  • 3,415
  • 10
  • 38
  • 62

1 Answers1

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?

Brian Berns
  • 15,499
  • 2
  • 30
  • 40
  • 1
    thank 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 Feb 20 '21 at 05: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 Feb 20 '21 at 05: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 Feb 20 '21 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 Feb 20 '21 at 21:53