从 App.config F# AppSettings 提供程序获取并使用连接字符串

Get and use connection string from App.config F# AppSettings provider

我已经在网上搜索了几个小时,还是做不到,所以我希望有人能帮我解决这个问题。

我试过直接使用 App.Config,但总是有 null return。所以我转向 AppSetting typerprovider。这确实 return 预期的字符串,但我有一个问题,到目前为止(通过 google)没有人有答案。

open System.Linq
open FSharp.Data.Sql
open MySql.Data
open FSharp.Configuration 
type Settings = AppSettings<"App.config">

let c = Settings.ConnectionStrings.RaspberryPi 

[<Literal>]
let connection = c //quick attempt to turn c into a literal.

type sql = SqlDataProvider< ConnectionString = c,  ResolutionPath = @"C:\Program Files (x86)\MySQL\MySQL Connector Net 6.9.7\Assemblies\v4.5\"  >

我收到消息 "This is not a valid constant expression or custom attribute value."

虽然我能够打印出 Appsettings 提供程序获得的设置,但我似乎无法使用它连接到数据库。

这是App.config:

<?xml version="1.0" encoding="utf-8"?>
<configuration>
    <startup> 
        <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.6" />
    </startup>
  <runtime>
    <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
      <dependentAssembly>
        <assemblyIdentity name="FSharp.Core" publicKeyToken="b03f5f7f11d50a3a" culture="neutral" />
        <bindingRedirect oldVersion="0.0.0.0-4.3.1.0" newVersion="4.3.1.0" />
      </dependentAssembly>
    </assemblyBinding>
  </runtime>
  <connectionStrings>
    <add name="raspberryPi" providerName="FSharp.Data.SqlProvider" connectionString="Server=SomeDB.rds.amazonaws.com:3306;Database=SomeDB;Uid=SomeUser;Pwd=APassword" />
  </connectionStrings>
</configuration>

我已经求助于 typeprovider,因为我之前使用 System.Configuration 读取文件的方法无法正常工作,即使我快速搜索输出文件夹并确保所有配置文件都已更新。

请注意,我也在使用 MySQL 类型的提供程序!

虽然我可以直接在代码中使用字符串,但我的理解是这对于生产代码来说是个糟糕的主意。

如有任何帮助,我们将不胜感激 - 我不介意承认,今天这已经耗费了几个小时,这让我非常惊讶。

注意 - 可能对其他人有帮助:我也看过 this answer, this article and this one from the MS Forums

不幸的是,这行不通。连接字符串由 read/write 静态 属性 (Settings.ConnectionStrings.RaspberryPi) 公开,不能将其视为 constant/literal(按设计)。

有人可以编写一个类型提供程序,通过将连接字符串公开为文字静态字段而不是 read/write 属性来执行您想要的操作,但这与更新应用程序设置不兼容,这似乎是现有提供商的目标。或许您可以考虑向 AppSettings 项目提交一个功能请求,以启用一个单独的模式来满足您的需求。