Search code examples
entity-frameworkf#type-providers

How can I make the Entity Framework Type Provider use the runtime config file?


I have an F# library project that I'm using from a C# web project. I would like to use the Entity Framework Type Provider in my F# project, and have it get the connection string from the Web.config - but I'm having trouble getting this working.

type internal FooDb = 
    SqlEntityConnection<ConnectionStringName="FooDb", Pluralize=true>

At design time, I'm required to have an App.config file in the F# library project with a connection string having the matching name.

At runtime, when calling my F# code from the C# web project, I get an error that it can't locate the "App.config" file. This surprises me, because I was expecting that at runtime it would just use ConfigurationManager.ConnectionStrings to load the connection string from the currently-active config file (in the case of a web app, Web.config). However this doesn't seem to be the case.

I tried adding the ConfigFile parameter:

type internal FooDb = 
    SqlEntityConnection<ConnectionStringName="FooDb", ConfigFile="Web.config", Pluralize=true>

But this just made it complain at design time that it couldn't find Web.config.

Then I renamed the App.config file in the F# library project to Web.config and that seems to have gotten things working. However, I'm uneasy about this solution. Is this really how it's intended to work? I have to have a web.config file in my library project? What would I do if I wanted to use the same library from a command-line executable, and in that environment the config file is called AssemblyName.exe.config?

Forcing me to hard-code the name of a config file that can have different names in different contexts seems very brittle, and a poor design. Please tell me I'm missing something.


Solution

  • The issue you've encountered seems rather unfortunate indeed, and I don't know whether you are missing something or not. However, the SqlEntityConnection documentation says that FooDb should have a GetDataContext overload where a "connectionString parameter may be used when the connection string is determined at runtime." Perhaps that will give you a decent enough work around (i.e. pass in the connection string from ConfigurationManager.ConnectionStrings yourself).