3
\$\begingroup\$

This code will check the database for an order number. If none exist it creates one. If one does exist then it will increment it by one and update the database. Is this the most efficient way to handle this?

// Order Number check
let updateOrderNumber bizLocId = 

    // order number record exist
    let numExist =
        query{
            for row in tool.db.Order_Order_OrderNumber do
            where(row.BusinessLocationId = bizLocId)
            count
        } 

    // retrieve number
    if numExist < 1 then
        let firstOrder =
            dbSchema.ServiceTypes.Order_Order_OrderNumber(
                BusinessLocationId = bizLocId,
                OrderNumber = 1
            )
        // save to db
        tool.insertRowIn tool.db.Order_Order_OrderNumber firstOrder
        tool.saveToDb ()
        1
    else
        let numRecord =
            query{
                for row in tool.db.Order_Order_OrderNumber do
                where(row.BusinessLocationId = bizLocId)
                select row
                exactlyOneOrDefault
            }
        // update order number in db
        let newOrderNumber = 
            numRecord.OrderNumber + 1
        numRecord.OrderNumber <- newOrderNumber
        tool.saveToDb ()

        newOrderNumber
\$\endgroup\$
3
  • 1
    \$\begingroup\$ I think you need to use transactions here. Otherwise, two instances of this running at the same time could create the same ID. \$\endgroup\$
    – svick
    Jun 18, 2014 at 18:05
  • \$\begingroup\$ @svick Can you provide an example? I'm new to F#. \$\endgroup\$ Jun 18, 2014 at 18:09
  • 1
    \$\begingroup\$ @user1206480 if your database supports it, you should use an auto-incrementing identity column for this rather than implementing it in code. Then, you would only have to insert new rows with the appropriate BusinessLocationId, and the OrderNumber would automatically generate for you. \$\endgroup\$
    – Dan Lyons
    Jul 28, 2014 at 18:06

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Browse other questions tagged or ask your own question.