I've written a T4 template where I instantiate an EF context to read some data. The problem is that the context cannot see the connection string from the Web.config.
How can I make the connection strings from the Web.config available to the template?
More info:
- template is written from scratch
- EF edmx is located in another project
- the first query I make in the template tells me that it cannot find the required connection string in the project where the template resides
Tried some of the solutions (thank you) below but I get this:
Error 2 Compiling transformation: 'Microsoft.VisualStudio.TextTemplating12165CB53B43A726CBA54A29800255D257AAFD4D5F0DACE4DFE5872F2DEC7739EDF358F49C0444A912B851939903A79BC6180FCEB3FD0D1BF8C0093741DDDACA.GeneratedTextTransformation' does not contain a definition for 'Host' and no extension method 'Host' accepting a first argument of type 'Microsoft.VisualStudio.TextTemplating12165CB53B43A726CBA54A29800255D257AAFD4D5F0DACE4DFE5872F2DEC7739EDF358F49C0444A912B851939903A79BC6180FCEB3FD0D1BF8C0093741DDDACA.GeneratedTextTransformation' could be found (are you missing a using directive or an assembly reference?)
I have the following declared:
<#@ assembly name="EnvDTE" #>
<#@ import namespace="EnvDTE" #>
<#@ import namespace="Microsoft.VisualStudio.TextTemplating" #>
If I include the assembly for Microsoft.VisualStudio.TextTemplating it tells me that it's already inserted.
Also, is there any way to make the ConfigurationManager available to the DbContext so he can read w/e he wants behind the scenes without me passing him the connection string?
Solved it, thanks again:
<#@ template hostspecific="true" language="C#" debug="false" #>
<#@ assembly name="System.Core.dll" #>
<#@ assembly name="System.Configuration" #>
<#@ import namespace="Microsoft.VisualStudio.TextTemplating" #>
<#@ import namespace="System.Configuration" #>
var map = new ExeConfigurationFileMap();
map.ExeConfigFilename = this.Host.ResolvePath(@"..\Web.config");
var config = ConfigurationManager.OpenMappedExeConfiguration(map, ConfigurationUserLevel.None);
var connectionString = config.ConnectionStrings.ConnectionStrings["MyConnectionName"].ConnectionString;