Home > Net >  Can not use DisplayAttribute in T4 template
Can not use DisplayAttribute in T4 template

Time:01-31

In my custom T4 template I have to read DisplayAttribute of a type. But I'm keep getting different errors after struggling with several solutions. Here is part of my .tt file :

<#@ template debug="true" hostspecific="true" language="C#" compilerOptions="/langversion:10" #>
<#@ assembly name="System" #>
<#@ assembly name="System.Runtime" #>
<#@ assembly name="System.Core" #>
<#@ assembly name="System.ComponentModel.Annotations" #>

<#@ import namespace="System" #>
<#@ import namespace="System.Reflection" #>
<#@ import namespace="System.Runtime" #>
<#@ import namespace="System.Linq" #>
<#@ import namespace="System.Text" #>
<#@ import namespace="System.Collections.Generic" #>
<#@ import namespace="System.ComponentModel.DataAnnotations" #> 
<#@ output extension=".cs" #>

<#
    static string GetEnumValueDisplayName(Enum value)
    {
        Type type = value.GetType();
        MemberInfo[] memInfo = type.GetMember(value.ToString());
        DisplayAttribute? dispalyAttribute = null;
        if (memInfo != null && memInfo.Length > 0)
        {
            object[] attrs = memInfo[0].GetCustomAttributes(typeof(DisplayAttribute), false);

            if (attrs != null && attrs.Length > 0)
                dispalyAttribute = attrs[0] as DisplayAttribute;
        }
        return dispalyAttribute?.Name ?? "";
    }
#>


<#
 foreach(myEnum en in Enum.GetValues(typeof(MyEnum)))
 {#>
          public static class <#[email protected]()#> { public const string Value = "<#[email protected]()#>";public const string Text = "<#=@GetEnumValueDisplayName(en)#>";}
<#}#>

And here is my compile time error :

Compiling transformation: The type name 'DisplayAttribute' could not be found in the namespace 'System.ComponentModel.DataAnnotations'. This type has been forwarded to assembly 'System.ComponentModel.DataAnnotations, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35' Consider adding a reference to that assembly.

I am using .net 6 with Visual Studio 2022(17.0.4).

CodePudding user response:

Remove <#@ assembly name="System.ComponentModel.Annotations" #> and add using System.ComponentModel.DataAnnotations; to the regular using statements.

enter image description here

CodePudding user response:

I am using .net 6

That would be a problem. The VS T4 engine only supports .NET Framework at this point, which means that it cannot load any .NET Core libraries during the transformation. We have started working on a .NET Core version of the engine but there is no ETA on when this would become available. Any updates would be communicated through this Suggestion Ticket.

  • Related