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

标签 c# sql-server entity-framework 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" #>

关于c# - 如何在 T4 中实例化 EF6 上下文?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28046634/

相关文章:

c# - 如何在 C# 中有效地获取字节数组的子集(前 N 个元素)?

sql-server - 最快的分层地理地址,最便宜的硬件上的数据查找? NoSQL 还是 SQL?

sql - 是否可以在 SQL PIVOT 中使用动态创建的值?

c# - 撤消上次数据库保存所做的更改

sql - 是否可以使用 Entity Framework 运行 native sql?

c# - Entity Framework 4 - 在哪里放置 "ApplyCurrentValues"逻辑?

c# - 类型 'System.Drawing.Graphics' 没有定义构造函数

c# - 如何控制 JSON.net 中大量异构对象的反序列化

c# - 将详细表读取到 ASP.NET MVC 5 Identity 2

SQL 服务器 : Get All views from All databases