如何在 T4 中实例化 EF6 上下文?

How to instantiate EF6 context in T4?

我想在 T4 模板中实例化一个新的 EF6 上下文,但出现以下错误:

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.

问题是无法实例化 Entity Framework 上下文,因为无法读取连接字符串。

我做了以下操作来获取连接字符串:

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;

但请确保您已导入以下内容以使上述代码正常工作:

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

还要确保您已引用所有 entity framework 个程序集:

<#@ 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" #>