Snippets

Cameron Presley Type Provider - Providing a dynamic connection string during runtime

Created by Cameron Presley last modified
// Need to have FSharp.Data.SqlClient package installed

open FSharp.Data

type Game = {id:int; name:string; numPlayers:int; playTime:int; publisher:string}
let gameOne = {id=2; name="Coup"; numPlayers=5; playTime=15; publisher=""}


// In order to use TypeProviders, you need to provide a constant for the connection.
[<Literal>]
let connectionString = @"Server=.\SQLExpress;Database=testDb;Integrated Security=True"

// Default instance will use the connection string for real-time checking
type GetAllGames = SqlCommandProvider<"Select * from Games", connectionString>

// Default instance will use the connection string for real-time checking
type InsertGame = SqlCommandProvider<"Insert into Games (Id, Name, NumPlayers, PlayTime, Publisher) Values(@Id, @Name, @NumPlayers, @PlayTime, @Publisher)", connectionString>

do
    // This will create a type provider pointing to where the connection string is
    use insertCmd = new InsertGame() // or new InsertGame('NewConnectionString')
    insertCmd.Execute(gameOne.id, gameOne.name, gameOne.numPlayers, gameOne.playTime, gameOne.publisher) |> ignore
    
    // This, on the other hand, will use the new connection. However, it does not provide any real-time checks
    use differentInsertCmd = new InsertGame("someNewConnectionString")
    differentInsertCmd.Execute(gameOne.Id, gameOne.name, gameOne.numPlayers, gameOne.playTime, gameOne.publisher) |> ignore
    
    use cmd = new GetAllGames ()
    cmd.Execute () |> printfn "%A"

Comments (0)

HTTPS SSH

You can clone a snippet to your computer for local editing. Learn more.