如何在T4模板中使用DbContext? [英] How to use DbContext in T4 template?

查看:91
本文介绍了如何在T4模板中使用DbContext?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用EntityFramework使用T4模板生成一些代码。我在与当前正在使用的EF6 DbContext相同的装配体中创建了一个T4模板:

I want to generate some code with a T4 Template using EntityFramework. I created a T4 Template in the same Assembly as my currently working EF6 DbContext:

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

运行它时,我得到以下执行:

When I run it, I get the following execption:


运行中的转换:System.InvalidOperationException:

Running transformation: System.InvalidOperationException:

实体框架提供程序的'Instance'成员类型
' System.Data.Entity.SqlServer.SqlProviderServices,
EntityFramework.SqlServer,Version = 6.0.0.0,Culture = neutral,
PublicKeyToken = b77a5c561934e089'没有返回
继承自'System'的对象.Data.Entity.Core.Common.DbProviderServices。
实体框架提供程序必须从此类继承,并且
实例成员必须返回提供程序的单例实例。
这可能是因为提供者不支持Entity Framework 6
或更高版本;请参阅 http://go.microsoft.com/fwlink/?LinkId=260882 更多
信息。

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之外,相同的上下文还可以。我想念的是什么?

The same context works fine outside of T4. What I am missing?

推荐答案

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

I've faced the same error, and the way to get it working was:


  1. 确保同时引用EntityFramework和
    上的提供程序DLL。这足以消除此错误。




<#@ assembly name="$(TargetDir)\EntityFramework.dll" #>
<#@ assembly name="$(TargetDir)\EntityFramework.SqlServer.dll" #>





  1. 配置由于T4在不同的上下文中运行,因此无法读取文件;因此,您需要创建一个接受连接字符串的DbContext构造函数;然后在T4中创建上下文时传递它

这篇关于如何在T4模板中使用DbContext?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆