c# - 如何在T4模板中使用DbContext?

标签 c# entity-framework dbcontext t4

我想使用 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 之外工作正常。我缺少什么?

最佳答案

我遇到了同样的错误,让它工作的方法是:

  1. 确保引用 EntityFramework 和您的提供者 DLL 您的 T4 模板;这足以消除此错误。
<#@ assembly name="$(TargetDir)\EntityFramework.dll" #>
<#@ assembly name="$(TargetDir)\EntityFramework.SqlServer.dll" #>
  1. 未读取配置文件,因为 T4 在不同的上下文中运行;因此,您需要创建一个接受连接字符串的 DbContext 构造函数;然后在 T4 中创建上下文时传递它

关于c# - 如何在T4模板中使用DbContext?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38103322/

相关文章:

c# - 动态端口转发 libssh C

c# - 将字符串从 C# 传递到 C DLL

c# - Entity Framework SaveChangesAsync 阻塞了我的 UI?

c# - Linq-to-SQL 中的 SubmitChanges 和 Entity Framework 中的 SaveChanges 之间的技术区别是什么?

mysql - 使用多个dbcontexts并且找不到原始数据库

c# - 不使用 SqlParameterCollection 时,SqlParameter 已包含在另一个 SqlParameterCollection 中

c# - 将 JSON 转换为对象,然后根据对象类型执行不同的操作

c# - 编写 XML 文档时如何在方法摘要中引用方法参数?

c# - 为什么在使用 Entity Framework 实现存储库模式时使用接口(interface)?

sql-server - DBContext SaveChanges 在内部是如何工作的?