c# - T4 模板错误 : loading the include file ef. utility.cs.ttinclude 返回了 null 或空字符串

标签 c# visual-studio-2010 t4

我已经覆盖了 Controller 生成 T4 模板 (ControllerWithContext.tt),如 here 所述.
我想利用在 POCO 模型生成器 T4 模板中使用的 EF.utility.CS.ttinclude 中的代码帮助实用程序。因此,我将以下行从我的 Model.tt 复制到我的 ControllerWithContext.tt

<#@ include file="EF.Utility.CS.ttinclude"#>

但是,当我尝试添加 Controller 时,我收到了错误消息

Loading the include file 'EF.utility.CS.ttinclude' returned a null or empty string

根据MSDN documentation ,这个错误是因为包含的文件是空白的,这显然不是因为它适用于 Model.tt

我能看到的唯一区别是重写的 ControllerWithContext.tt 没有定义自定义工具,而 Model.tt 将其设置为 TextTemplatingFileGenerator.

我的解决方法是将我需要的函数从 ef.utility.cs.ttinclude 复制到我的 ControllerWithContext.tt 中,这本身会引发更多错误,但很容易解决。

如何在没有定义自定义工具的情况下包含 T4 模板?

最佳答案

遵循@DustinDavis 的建议,并使用在 OlegSych's site 上找到的宝贵信息,这是我所做的:

  • 创建了一个名为 CodeGenerationTools 的新项目。
  • 将项目引用添加到

    • 系统.数据.实体.设计
    • 环境数据工程师
    • 系统.数据.实体
    • Microsoft.VisualStudio.TextTemplating.10.0

    对于最后的引用,我必须安装正确版本的 Visual Studio SDK

  • 将 EF.Utility.CS.ttinclude 文件复制到项目中。
  • 将其重命名为 CodeGenerationTools.cs
  • 编辑文件并转换所有<#@ import namespace="<name>" #>using <name>;
  • 删除开闭<#+ #>
  • 添加指令 using Microsoft.VisualStudio.TextTemplating;
  • 扩展类:

    public class CodeGenerationTools : TextTransformation
    
  • 覆盖 TransformText方法

    public override string TransformText() {
        throw new NotImplementedException();
    }
    
  • 添加了空构造函数

    public CodeGenerationTools() {
        _textTransformation = DynamicTextTransformation.Create(this);
        _code = new CSharpCodeProvider();
        _ef = new MetadataTools(_textTransformation);
        FullyQualifySystemTypes = false;
        CamelCaseFields = true;
    }
    
  • 最后,构建这个项目。

接下来的步骤发生在主项目中 - 编辑了 T4 模板文件。 - 将模板指令更改为

    <#@ template language="C#" HostSpecific="True" debug="false" inherits="CodeGenerationTools"#>

- 添加了指令

    <#@ assembly name="C:\Visual Studio 2010\Projects\CodeGenerationTools\CodeGenerationTools\bin\Debug\CodeGenerationTools.dll" #>
    <#@ import namespace="CodeGenerationTools" #>

所有这些现在意味着我可以在我自己的 T4 模板中使用 EF.Utility.CS.ttinclude 中的辅助方法,并且我有办法添加我自己的辅助方法,这些方法将可用于所有项目。

关于c# - T4 模板错误 : loading the include file ef. utility.cs.ttinclude 返回了 null 或空字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8078858/

相关文章:

c# - 获取配置文件的路径时使用 AppDomain 和 ConfigurationManager 有什么区别?

c# - 使用正则表达式迭代字符串并搜索 3 个连续的连字符并将其替换为 [space][hyphen][space]

c# - WPF 设计器代码一直告诉我有错误

asp.net-mvc - 用于 ASP.NET MVC 的 Spark T4 模板

c# - T4 预处理模板调试不起作用 - Visual Studio 2010 RTM

C# 如何添加一个ListView ClickListener

c# - 轻量级 .NET Web 开发?

c++ - 如何在 XCode/Visual Studio 之间保持跨平台库同步

c++ - 在 C 和 C++ 库之间共享变量的困境

c# - 使用 TransformOnBuild 时无法引用 T4 模板中的依赖项程序集