How to use DbContext in T4 template?

五迷三道 提交于 2020-01-13 18:54:11

问题


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:

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.

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


回答1:


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

  1. Ensure to reference both EntityFramework, and your provider DLLs on Your T4 template; This is enough to get rid of this error.
<#@ assembly name="$(TargetDir)\EntityFramework.dll" #>
<#@ assembly name="$(TargetDir)\EntityFramework.SqlServer.dll" #>
  1. Config files aren't read since T4 runs in a different context; hence you'll need to create a DbContext constructor accepting a connection string; then you pass it while creating the context in T4


来源:https://stackoverflow.com/questions/38103322/how-to-use-dbcontext-in-t4-template

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!