我想使用 EntityFramework 使用 T4 模板生成一些代码。我在与当前工作的 EF6 DbContext 相同的程序集中创建了一个 T4 模板:
<#@ template language="C#" hostspecific="true" debug="True" #>
<#@ assembly name="$(SolutionDir)\packages\EntityFramework.6.1.3\lib\net45\EntityFramework.dll" #>
<#@ assembly name="$(TargetPath)" #>
<#@ import namespace="Conwell.Administration.Data.Entities" #>
<#
using (var db = new KassenautomatEntities())
{
#>
//Hello World
<#
}
#>
当我运行它时,我得到以下执行:
Running transformation: 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. This may be because the provider does not support Entity Framework 6 or later; see http://go.microsoft.com/fwlink/?LinkId=260882 for more information.
相同的上下文在 T4 之外工作正常。我缺少什么?
最佳答案
我遇到了同样的错误,让它工作的方法是:
- 确保引用 EntityFramework 和您的提供者 DLL 您的 T4 模板;这足以消除此错误。
<#@ assembly name="$(TargetDir)\EntityFramework.dll" #> <#@ assembly name="$(TargetDir)\EntityFramework.SqlServer.dll" #>
- 未读取配置文件,因为 T4 在不同的上下文中运行;因此,您需要创建一个接受连接字符串的 DbContext 构造函数;然后在 T4 中创建上下文时传递它
关于c# - 如何在T4模板中使用DbContext?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38103322/