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

我想在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.

解决方法

问题是无法实例化实体框架上下文,因为无法读取连接字符串.

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

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

还要确保已引用所有实体框架程序集:

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

相关文章

目录简介使用JS互操作使用ClipLazor库创建项目使用方法简单测...
目录简介快速入门安装 NuGet 包实体类User数据库类DbFactory...
本文实现一个简单的配置类,原理比较简单,适用于一些小型项...
C#中Description特性主要用于枚举和属性,方法比较简单,记录...
[TOC] # 原理简介 本文参考[C#/WPF/WinForm/程序实现软件开机...
目录简介获取 HTML 文档解析 HTML 文档测试补充:使用 CSS 选...