I am using VS 2010 (C#) T4 templates to generate code.
I need to iterate through all types within my project, shortlist entity poco classes and generate wrappers. The problem is, the project namespace is not being recognized.
Here is the solution structure:
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
}
Here is the text template:
<#@ 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; }
}
}
The above code generates an error: The type or namespace ‘MySolution’ cannot be found. Are you missing a using directive or an assembly reference? I then put the following line of code to include the assembly:
<#@ Assembly Name="..\MySolution.Entities\bin\x86\Release\MySolution.Entities.dll" #>
Now it gives me a different error: The host threw an exception while trying to resolve the assembly reference ‘..\..\..TrafficMonitor.Core\bin\x86\Release\TrafficMonitor.Library.dll’. The transformation will not be run. The following Exception was thrown:
System.IO.FileLoadException: The given assembly name or codebase was invalid. (Exception from HRESULT: 0x80131047)
Any ideas on how to overcome this limitation?
The error is because the T4 template processor is unable to find your assembly.
It should find the assembly if you use the full path to the assembly in the Assembly directive in your T4 template. A better approach to using the full path is to use the one of the Visual Studio macro variables, such as $(SolutionDir), which will be expanded when your T4 template is executed.