使用来自 app.config 的连接字符串和 FSharp.Data.SqlClient

Using connectionstring from app.config with FSharp.Data.SqlClient

我正在使用 FSharp.Data.SqlClient 并尝试将我的 connectionString 从 [<Literal>] 移动到 app.config。

我的app.config看起来像这样

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <connectionStrings>
    <add name="DefaultConnection" connectionString="Data Source=(localdb)\MSSQLLocalDB;Initial Catalog=Test;Integrated Security=True" providerName="System.Data.SqlClient"/>
  </connectionStrings>
    <startup>
        <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.6.2" />
    </startup>
</configuration>

而我的SqlCommandProvider如下所示,根据http://fsprojects.github.io/FSharp.Data.SqlClient/configuration%20and%20input.html

应该是正确的
new SqlCommandProvider<"SELECT ...", 
       ConnectionStringOrName = "name=DefaultConnection", 
       SingleRow = true, 
       AllParametersOptional = true>(??????)

现在问题来了。最后一部分是什么,?????? 部分。

我试过 "name=DefaultConnection" 但它给我一个运行时错误,名称不受支持。

我似乎找不到任何解释其中内容的文档。

更新

为了解决问题,我发现了这个解决方法。 https://fsprojects.github.io/FSharp.Configuration/

如果您无论如何都必须提供连接字符串,我不明白 ConnectionStringOrName 的目的。还有为什么你必须指定它两次。对我来说意义不大:(

使用类型提供程序时,您通常需要两个单独的数据源:

  • 编译时一个在编辑代码和编译代码时使用。类型提供程序使用此连接或数据源来推断数据的模式 - 在 SQL 提供程序的情况下,这是与数据库的连接,用于检查所有列名是否存在等。

  • 运行-一次用于当你实际运行程序部署到某处后。这是您将从中读取实际数据的地方。

您需要两个的原因是 运行 时间数据源可能在 运行 时间确定并且可能无法在编译时访问(您通常可以访问开发数据库,​​而不是生产数据库)。编译时连接需要是一个常量,以便提供者可以使用它(在编译您的代码时)而无需 运行ing 您的代码的任何部分。

如果是 SQL 命令提供程序:

type SelectCmd = SqlCommandProvider<"SELECT ...", 
   ConnectionStringOrName = "name=DefaultConnection", 
   SingleRow = true, 
   AllParametersOptional = true>

let cmd = new SelectCmd(??????)
  • "name=DefaultConnection" 告诉提供者在编译时使用 app.config 密钥
  • ?????是需要指定运行时的连接字符串

要从 app.config 读取连接字符串,您可以使用标准 .NET 方法 like using ConfigurationManager:

open System.Configuration

let conn = ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString;
let cmd = new SelectCmd(conn)

将连接字符串传递给 SqlCommandProvider 时,这样的事情不会起作用,因为这需要 运行 一些代码来读取字符串,而这只有在 运行 时才有可能.这就是为什么 SQL 命令提供程序有一个方便的选项来将 name=DefaultConnection 指定为特殊字符串。