Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Retrieving property type from CodeProperty in T4 template

I'm implementing some fairly straight forward code generation using T4, but I'm stuck on a basic problem when it comes to the details of Property generation. When I access the Type property on the CodeProperty objects I want to generate, they are returning 'System.__ComObject' instead of the actual type of the property.

I'm using EnvDTE to find all classes in the project that include my custom attribute. I'm using this to mark certain classes for code generation. So far so good. I'm then stepping over all the CodeElement objects that are the Children of my class. I can find all the properties, it's just I can't get the 'Type' of them.

Here's a snippet of my T4:

public class <#= cls.Name #>_DTO
{
<#
    foreach (CodeElement child in cls.Children)
    {
        if (child.Kind == vsCMElement.vsCMElementProperty)
        {
            var prop = child as CodeProperty;
#>

    public <#= prop.Type.ToString() + " " + child.Name #> { get; set; }

<#
    }
  }
}
#>

And a sample of the output is:

public class TestResult_DTO
{
    public System.__ComObject TestType { get; set; }
}

As you can see, I'm close to valid output, it's just the Type of the property that I'm struggling to access.

like image 594
eddie.sholl Avatar asked Mar 03 '14 07:03

eddie.sholl


People also ask

What is transform all T4 templates?

t4 is basically a tool built into VS for doing text transformation, typically for doing code generation. Transform All T4 Templates searches your solution for *. tt files and executes them to create other text, again typically source code, files.

What are T4 templates in Entity Framework?

T4 templates in entity framework are used to generate C# or VB entity classes from EDMX files. Visual Studio 2013 or 2012 provides two templates- EntityObject Generator and DBContext Generator for creating C# or VB entity classes. The additional templates are also available for download.

What is the purpose of using T4 templates?

We use this template to generate the code when we add a view or controller in MVC. The file extension of this template is tt. Basically when we add a view or controller using a scaffhold template it is called a T4 template. By using this template if we add a controller or view then it generates some code automatically.


1 Answers

Looking at the docs, I suspect you want AsString instead of ToString(). That would call CodeTypeRef.AsString:

AsString return a string representation for the CodeTypeRef in the language being modeled. For example, if the vsCMTypeRef type is vsCMTypeRefInt, then the string would be "Int" for Visual C# and "Long" for Visual Basic.

I've never written this sort of code myself so I'm just going by the documentation, but it's worth a try :)

like image 79
Jon Skeet Avatar answered Sep 24 '22 04:09

Jon Skeet