Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SqlDataConnection type provider - setting database connection string with script parameter

The normal way of using a SqlDataConnection type provider is as follows:

type dbSchema = SqlDataConnection<"Data Source=MYSERVER\INSTANCE;InitialCatalog=MyDatabase;Integrated Security=SSPI;">
let db = dbSchema.GetDataContext()

However we have a problem which is we want to use this type provider in an f# script where the connection string for the database is passed as a parameter. So what I would like to do is something like this:

let connectionString= Array.get args 1
type dbSchema = SqlDataConnection<connectionString>

However it gives the error "This is not a constant expression or valid custom attribute value"

Is there any way to do this?

like image 790
bstack Avatar asked Nov 27 '14 12:11

bstack


2 Answers

Unfortunately there's no way to do this, the type provider requires a compile time literal string. This is so that when you're compiling the application, the type provider's able to connect and retrieve the metadata about the database and generate the types for the compiler. You can choose to extract out the connection string into a string literal by writing it in the form

[<Literal>] let connString = "Data Source=..."
type dbSchema = SqlDataConnection<connString>

Assuming your 2 databases have the same schema, it's then possible to supply your runtime connection string as a parameter to the GetDataContext method like

let connectionString = args.[1]
let dbContext = dbSchema.GetDataContext(connectionString)
like image 123
bruinbrown Avatar answered Jan 02 '23 16:01

bruinbrown


The way i've been doing it is i have a hardcoded literal string (using the "Literal" attribute) for design time use and use a local string from the configuration when getting the data context. I use a local db schema (also hardcoded) to speed up intelli-sense during development.

type private settings = AppSettings<"app.config">
let connString = settings.ConnectionStrings.MyConnectionString
type dbSchema = Microsoft.FSharp.Data.TypeProviders.SqlDataConnection<initialConnectionString, Pluralize = true, LocalSchemaFile = localDbSchema , ForceUpdate = false, Timeout=timeout>
let indexDb = dbSchema.GetDataContext(connString);
like image 32
FistOfFury Avatar answered Jan 02 '23 18:01

FistOfFury