问题
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:
- 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" #>
- 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