回答

收藏

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

技术问答 技术问答 115 人阅读 | 0 人回复 | 2023-09-13

我正在编写要与Azure Worker角色一起使用的F#。我希望类将连接字符串a作为参数。我创建一个数据库连接9 _. A; T4 h; V) a
type dbSchema = SqlDataConnection" q2 }: v- p$ b# I) e8 A
let db = dbSchema.GetDataContext()  |+ R( U, z  p: r0 x* y7 e. O
但是dbSchema是一种类型,因此无法将其嵌入到我的类中(另一种类型)。我可以创建两个单独的模块,一个与数据库连接,另一个与我的课程
9 L, c9 u+ h' o+ [6 G8 ymodule DataSource =
3 b9 ]$ I' O0 W: q0 G    []
* o& H8 h9 R$ K0 ^    let connectionString = "Data Source=.\SQLEXPRESS;Initial Catalog=Service;Integrated Security=True"
  E" B7 P& y  n, U. T8 `    type dbSchema = SqlDataConnection
' f- h& B* s+ Q8 L6 d    let db = dbSchema.GetDataContext()9 ]; L7 D/ q3 q
module DealerFactory =
; ]% j  {5 m1 O& k# O* d8 q    type Factory(connectionString) =4 Q% |+ D9 c9 V# a$ A5 y
        member this.GetList(latitudeLeftTop, longitudeLeftTop, latitudeRightBottom, longitudeRightBottom) =
* w. k* D- V% a        "..". w9 I  i( T8 \+ O  D- j4 w& g
但是,如何在类的构造函数中使用connectionString创建连接?
% e$ D, E. v/ m% N                7 n6 n3 A) F* L, I. O6 P2 Q' H6 V
解决方案:  S" A1 F' d. M) @
                " a/ I7 u, O& c+ }$ u) x2 ^
. U3 k$ Y+ h9 {, q

9 \4 f6 x* R& @9 ]/ `+ a/ L                SQL数据库的类型提供程序将连接字符串用于两个不同的目的。首先,它需要一个(在编译时)来生成数据库模式。其次,您可以(可选)给它另一个供您在实际运行程序时在运行时使用。4 K( |0 m) [& Y0 S& ?$ D* ?
需要在中指定编译时连接字符串作为参数,SqlDataConnection并且可以将运行时连接字符串传递给GetDataContext(...)操作。: x7 b' \8 {# a1 k; R1 ^6 A
因此,您可以使用静态已知的编译时连接字符串来定义类型:. F3 \/ P; s" c
[]4 T8 w/ M; q% Y/ m4 X/ t- z
let connectionString = "Data Source=.\SQLEXPRESS;Initial Catalog=Service; ..."
' r" w$ i' k2 h4 vtype dbSchema = SqlDataConnection" d$ a. B0 `! L+ \
而且,当您要创建数据库连接的实例时,可以向其传递另一个连接字符串:+ @# R( s. u2 D. b2 b: d
type Factory(connectionString) =' l2 h  d; p+ G  b. K
  // Create connection to the DB using (a different). J- a6 @6 k# `4 t* m
  // connection string specified at runtime0 T1 ~; n6 l% k$ B% A( b
  let db = dbSchema.GetDataContext(connectionString)
3 ~% d: D; ]0 J* i+ M9 w2 c  member this.GetList( latitudeLeftTop, longitudeLeftTop, 4 N7 m0 x( _8 [7 C8 `% T4 S& ]# b
                       latitudeRightBottom, longitudeRightBottom) =2 g3 d' n" c4 `5 W8 Z( E) r
    // Use local 'db' to access the database
. c5 Z- h. i$ K: ]3 A% f    query { for v db.Table do select v }) e6 R4 X* B7 H" N) l+ h' u
与您的原始代码(db在模块中具有值)相比,这会db为each创建一个新的实例Factory,但是我想如果Factory将连接字符串作为参数,这是可以预期的。
分享到:
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则