应该如何将F#SqlDataConnection TypeProvider与App.Config文件一起使用? [英] How is one supposed to use the F# SqlDataConnection TypeProvider with an App.Config file?
问题描述
我正在使用类型表达式:
I am using the type expression:
type dbSchema = SqlDataConnection<ConnectionStringName="X1", ConfigFile="App.config">
这在编译时效果很好(我拥有对所有数据库类型的完全访问权限),但在运行时失败.我猜这是因为在控制台应用程序的bin
目录中生成的配置文件被命名为其他名称,例如MyAppName.exe.config
,因此找不到App.config
文件.
This works great at compile time (I have full access to all the db types), but it fails at run time. I presume it's because the config file generated in the console application's bin
directory is named something else, such as MyAppName.exe.config
, and therefore the App.config
file is not found.
当然,对于使用web.config
的 ASP.NET MVC 类型的应用程序,没有问题,因为编译和运行时配置文件名相同.
Certainly, for an ASP.NET MVC type app that uses web.config
, there's no issue because the compile and runtime config filenames are the same.
幸运的是,在bin
目录中放置重复的App.config
确实可以解决问题,但这是我们所期望的吗?有什么想法吗?
Fortunately, placing a duplicate App.config
in the bin
directory does remediate the problem, but is that what we are expected to do? Any thoughts?
推荐答案
关于类型提供程序定义的工作方式的描述具有误导性-typedef中的值实际上仅在代码/编译时才有效,而在运行时则作为默认值.但是,您已经注意到,在运行时查找正确的配置文件不是很聪明.
The description of how the type provider definition works is misleading - the value in the typedef really only matters at code/compile time, and as a default at runtime. However, as you've noted, it isn't very smart about finding the correct config file at runtime.
您可以通过将连接字符串作为参数传递给GetDataContext来完成所需的操作:
You can accomplish what you want by passing the connection string as a parameter to GetDataContext:
type dbSchema = SqlDataConnection<ConnectionStringName="X2">
let db = dbSchema.GetDataContext(ConfigurationManager.ConnectionStrings.["X2"].ConnectionString)
...或者如果您也想使其在F#交互式环境中工作,请像这样包装它:
...or if you also want to make it work in F# interactive, wrap it like so:
type dbSchema = SqlDataConnection<ConnectionStringName="X2">
#if COMPILED
let db = dbSchema.GetDataContext(ConfigurationManager.ConnectionStrings.["X2"].ConnectionString)
#else
let db = dbSchema.GetDataContext()
#endif
(请注意,您将需要引用System.Configuration.)
(Note that you will need a reference to System.Configuration.)
这篇关于应该如何将F#SqlDataConnection TypeProvider与App.Config文件一起使用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!