[英]Sql F# Type Provider, App.Config, and ConnectionStrings?
[英]F# Type Provider for SQL in a class
我正在编写要与Azure Worker角色一起使用的F#。 我希望类将连接字符串a作为参数。 我创建一个数据库连接
type dbSchema = SqlDataConnection<"...">
let db = dbSchema.GetDataContext()
但是dbSchema是一种类型,因此无法将其嵌入到我的类中(另一种类型)。 我可以创建两个单独的模块,一个与数据库连接,另一个与我的课程
module DataSource =
[<Literal>]
let connectionString = "Data Source=.\SQLEXPRESS;Initial Catalog=Service;Integrated Security=True"
type dbSchema = SqlDataConnection<connectionString>
let db = dbSchema.GetDataContext()
module DealerFactory =
type Factory(connectionString) =
member this.GetList(latitudeLeftTop, longitudeLeftTop, latitudeRightBottom, longitudeRightBottom) =
".."
但是,如何在类的构造函数中使用connectionString创建连接?
SQL数据库的类型提供程序将连接字符串用于两个不同的目的。 首先,它需要一个(在编译时)来生成数据库模式。 其次,您可以(可选)给它另一个供您在实际运行程序时在运行时使用。
需要在SqlDataConnection<...>
中将编译时连接字符串指定为参数,并且可以将运行时连接字符串传递给GetDataContext(...)
操作。
因此,您可以使用静态已知的编译时连接字符串来定义类型:
[<Literal>]
let connectionString = "Data Source=.\SQLEXPRESS;Initial Catalog=Service; ..."
type dbSchema = SqlDataConnection<connectionString>
当您要创建数据库连接的实例时,可以向其传递另一个连接字符串:
type Factory(connectionString) =
// Create connection to the DB using (a different)
// connection string specified at runtime
let db = dbSchema.GetDataContext(connectionString)
member this.GetList( latitudeLeftTop, longitudeLeftTop,
latitudeRightBottom, longitudeRightBottom) =
// Use local 'db' to access the database
query { for v db.Table do select v }
与原始代码(在模块中使用db
值)相比,这会为每个Factory
创建一个新的db
实例,但是我想如果Factory
将连接字符串作为参数,这是可以预期的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.