简体   繁体   中英

T4 Template If Else statement to write out object instead of text?

I am trying to get the If else statement to compute the value based off the object passed in from the loop. This template worked until i added in the if else block and it says it can't be used as a statement. Thoughts??

<#@ template language="C#" #>
<#@ assembly name="System.Core" #>
<#@ import namespace="System.Linq" #>
<#@ import namespace="System.Text" #>
<#@ import namespace="System.Collections.Generic" #>
<#@ import namespace="CookieCutterDT" #>
<#@ import namespace="CookieCutterBL.DT_Template" #>

namespace <#= NameSpace #>
{
    public class <#= ClassName #>
    {
<#
        foreach(ColumnDT c in Columns)
    {#>
        public <# if (c.IsNullable && c.DataType != "string" && c.DataType != "string []") { c.DataType + "?"; } else { c.DataType; } #> <#= c.ColumnName #> { get; set; };
<#
    }
#>
    }
}

The if else is checking if the column is a nullable field and if it is, make it's datatype also nullable in C#.

The expressions in the if 's then/else parts won't generate code. You should write it like this:

public <# if (c.IsNullable && c.DataType != "string" && c.DataType != "string []") { #>
    <#= c.DataType + "?" #>
<# } else { #> 
    <#= c.DataType #>
<# } #> <#= c.ColumnName #> { get; set; };

Or, use the conditional operator ?: for a shorter alternative is:

<#= (c.IsNullable && c.DataType != "string" && c.DataType != "string []") ? (c.DataType + "?") : c.DataType #>

I was able to solve this myself, just came across an article that gave me the idea to try the .Write method and bam it works!! Just in case others run into a similar issue.

public <# if (c.IsNullable && c.DataType != "string" && c.DataType != "string []") { this.Write(c.DataType + "?"); } else { this.Write(c.DataType); } #> <#= c.ColumnName #> { get; set; };

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM