【问题标题】:How to instantiate EF6 context in T4?如何在 T4 中实例化 EF6 上下文?
【发布时间】:2015-03-18 18:10:41
【问题描述】:

我想在 T4 模板中实例化一个新的 EF6 上下文,但出现以下错误:

System.InvalidOperationException:实体框架提供程序类型“System.Data.Entity.SqlServer.SqlProviderServices,EntityFramework.SqlServer,Version=6.0.0.0,Culture=neutral,PublicKeyToken=b77a5c561934e089”的“Instance”成员未返回从“System.Data.Entity.Core.Common.DbProviderServices”继承的对象。实体框架提供者必须从此类继承,并且“实例”成员必须返回提供者的单例实例。

【问题讨论】:

    标签: c# sql-server entity-framework t4


    【解决方案1】:

    问题是无法实例化实体框架上下文,因为无法读取连接字符串。

    我做了以下获取连接字符串:

    var map = new ExeConfigurationFileMap();
    map.ExeConfigFilename = this.Host.ResolvePath(@"..\..\Web.config");
    
    var config = ConfigurationManager.OpenMappedExeConfiguration(map, ConfigurationUserLevel.None);
    var connectionString = config.ConnectionStrings.ConnectionStrings["BrainPerformEntities"].ConnectionString;
    

    但请确保您已导入以下内容以使上述代码正常工作:

    <#@ import namespace="Microsoft.VisualStudio.TextTemplating" #>
    <#@ import namespace="System.Configuration" #>
    <#@ import namespace="System" #>
    

    还要确保您已经引用了所有实体框架程序集:

    <#@ assembly name="$(MSBuildProjectDirectory)\bin\EntityFramework.dll" #>
    <#@ assembly name="$(MSBuildProjectDirectory)\bin\EntityFramework.SqlServer.dll" #>
    
    <#@ assembly name="System.Core.dll" #>
    <#@ assembly name="System.Configuration" #>
    <#@ assembly name="System.Data.dll" #>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-07-17
      • 2020-10-04
      • 2021-09-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多