【问题标题】:T4 engine not recognizing current project namespaceT4 引擎无法识别当前项目命名空间
【发布时间】:2013-02-01 01:38:23
【问题描述】:

我正在使用 VS 2010 (C#) T4 模板来生成代码。

我需要遍历我的项目中的所有类型,将实体 poco 类列入候选名单并生成包装器。问题是,项目名称空间未被识别。

解决方案结构如下:

namespace MySolution.Entities
{
    public class Employee { ... }
    public class Department { ... }
}

// Seperate project referenceing MySolution.Entities.
namespace MySolution.Database
{
    public partial class Context { ... }

    // Should generate Context.cs as a partial class with after iterating Syste.Types available in MySolution.Entities.
    Context.tt
}

这是文本模板:

<#@ template language="C#" #>
<#@ Output Extension=".cs" #>

namespace MySolution.Database
{
    public partial class Context:
        System.Data.Entity.DbContext
    {
<#
System.Type [] types = typeof(MySolution.Entities).Assembly.GetTypes();
for (int i=0; i < types.Count; i++)
#>
        public <#= types[i].Name; #> <#= types[i].Name; #> { get; set; }
    }
}

以上代码生成错误:找不到类型或命名空间“MySolution”。您是否缺少 using 指令或程序集引用?然后我将以下代码行包含在程序集中:

<#@ Assembly Name="..\MySolution.Entities\bin\x86\Release\MySolution.Entities.dll" #>

现在它给了我一个不同的错误:主机在尝试解析程序集引用“..\..\..TrafficMonitor.Core\bin\x86\Release\TrafficMonitor.Library.dll”时抛出异常。转换将不会运行。引发了以下异常: System.IO.FileLoadException:给定的程序集名称或代码库无效。 (HRESULT 异常:0x80131047)

关于如何克服这个限制的任何想法?

【问题讨论】:

    标签: c# .net entity-framework-5 t4 self-reference


    【解决方案1】:

    错误是因为 T4 模板处理器无法找到您的程序集。

    如果您在 T4 模板的 Assembly 指令中使用程序集的完整路径,它应该会找到该程序集。使用完整路径的更好方法是使用 Visual Studio 宏变量之一,例如 $(SolutionDir),它会在执行 T4 模板时展开。

    <#@ Assembly Name="$(SolutionDir)MySolution.Entities\bin\x86\Release\MySolution.Entities.dll" #>
    

    【讨论】:

    • T4 是与 C# 松散耦合的工具。这通常是一件好事。为了实现你喜欢做的事情,我会使用 roslyn。
    【解决方案2】:

    您不能静态引用尚未编译的程序集(请记住,T4 在编译程序集之前运行) 有一篇不错的文章,你可以在How to use T4 to generate Decorator classes考虑一下

    您也不应该通过&lt;#@ Assembly Name 引用程序集,因为T4 将对您已经编译的程序集进行操作,但T4 在编译之前操作。因此,您的工作流程将是 - 编译应用程序,运行 t4,使用来自 t4 的新源重新编译应用程序。每次修改源代码后,T4都在运行。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-09-17
      • 2014-01-21
      • 2019-12-19
      • 2011-10-06
      • 2020-09-21
      • 1970-01-01
      • 2013-06-26
      相关资源
      最近更新 更多