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

2

5

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#.

Verniavernice answered 2/3, 2016 at 22:20 Comment(0)
C
13

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 #>
Cuttle answered 2/3, 2016 at 22:28 Comment(2)
Interesting i couldn't get the ?: operator to compile but probably just me coding it wrong..just learning T4. I'll try this method also just to check it out :)Verniavernice
it works! I'll mark this as answer, like the solution and syntax more than my own discovery.Verniavernice
V
0

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; };
Verniavernice answered 2/3, 2016 at 22:28 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.