4
votes

I want to instantiate a new EF6 context in a T4 template but I get the following error:

System.InvalidOperationException: The 'Instance' member of the Entity Framework provider type 'System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089' did not return an object that inherits from 'System.Data.Entity.Core.Common.DbProviderServices'. Entity Framework providers must inherit from this class and the 'Instance' member must return the singleton instance of the provider.

1

1 Answers

1
votes

The problem was that the Entity Framework context could not be instantiated because the connection string could not be read.

I did the following to obtain the connection string:

var map = new ExeConfigurationFileMap();
map.ExeConfigFilename = this.Host.ResolvePath(@"..\..\Web.config");

var config = ConfigurationManager.OpenMappedExeConfiguration(map, ConfigurationUserLevel.None);
var connectionString = config.ConnectionStrings.ConnectionStrings["BrainPerformEntities"].ConnectionString;

But make sure you have imported the following in order for the above code to work:

<#@ import namespace="Microsoft.VisualStudio.TextTemplating" #>
<#@ import namespace="System.Configuration" #>
<#@ import namespace="System" #>

Also make sure you have referenced all entity framework assemblies:

<#@ assembly name="$(MSBuildProjectDirectory)\bin\EntityFramework.dll" #>
<#@ assembly name="$(MSBuildProjectDirectory)\bin\EntityFramework.SqlServer.dll" #>

<#@ assembly name="System.Core.dll" #>
<#@ assembly name="System.Configuration" #>
<#@ assembly name="System.Data.dll" #>