简体   繁体   English

类中SQL的F#类型提供程序

[英]F# Type Provider for SQL in a class

I am writing a F# to be used with Azure Worker role. 我正在编写要与Azure Worker角色一起使用的F#。 I want the class to have the connection string a as a parameter. 我希望类将连接字符串a作为参数。 I create a db connection with 我创建一个数据库连接

type dbSchema = SqlDataConnection<"...">
let db = dbSchema.GetDataContext()

but dbSchema is a type so it cannot be embeded in my class (another type). 但是dbSchema是一种类型,因此无法将其嵌入到我的类中(另一种类型)。 I can create two separate modules, one with the db connection and another one with my class 我可以创建两个单独的模块,一个与数据库连接,另一个与我的课程

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) =
        ".."

But how do I use the connectionString in my class' constructor to create the connection? 但是,如何在类的构造函数中使用connectionString创建连接?

The type provider for SQL database uses connection string for two different purposes. SQL数据库的类型提供程序将连接字符串用于两个不同的目的。 First, it needs one (at compile time) to generate the database schema. 首先,它需要一个(在编译时)来生成数据库模式。 Second, you may (optionally) give it another one to use at runtime when actually running the program. 其次,您可以(可选)给它另一个供您在实际运行程序时在运行时使用。

The compile-time connection string needs to be specified as parameter in SqlDataConnection<...> and the run-time connection string can be passed to GetDataContext(...) operation. 需要在SqlDataConnection<...>中将编译时连接字符串指定为参数,并且可以将运行时连接字符串传递给GetDataContext(...)操作。

So, you can define your type using statically known compile-time connection string: 因此,您可以使用静态已知的编译时连接字符串来定义类型:

[<Literal>]
let connectionString = "Data Source=.\SQLEXPRESS;Initial Catalog=Service; ..."
type dbSchema = SqlDataConnection<connectionString>

And when you want to create an instance of the DB connection, you can pass it another connection string: 当您要创建数据库连接的实例时,可以向其传递另一个连接字符串:

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 }

Compared with your original code (with the db value in a module), there is a difference that this creates a new db instance for every Factory , but I guess this is expected if Factory takes the connection string as an argument. 与原始代码(在模块中使用db值)相比,这会为每个Factory创建一个新的db实例,但是我想如果Factory将连接字符串作为参数,这是可以预期的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM