I’m dynamically creating class and variable names within my code blocks For example:
if (new<#=et.Name#> == null)
For an entity model named Site, this generates:
if (newSite == null)
But what I want to do is evaluate the type of item, and then gen the code based on that type. For my specific purposes, I want to write a block of code that’ll create a new Primary Key on the fly based on the datatype of the key value for that entity. So I want to do something like this in my template:
<#if ( new<#=et.Name#>.<#=primaryKey.Name#>.GetType() == typeof( Guid ) ) {#>
if (new<#=et.Name#>.<#=primaryKey.Name#> == Guid.Empty )
new<#=et.Name#>.<#=primaryKey.Name#> = Guid.NewGuid();
<#} #>
The subsequent generated code for an entity model named Site would look like this:
if ( newSite.SiteKey == Guid.Empty )
newSite.SiteKey = Guid.NewGuid();
This logically looks as if it’ll work. However, I haven’t been able to find the correct syntax to have nested template blocks and have those values evaluated and then placed within the conditional. Notice the Expression Block nested within the Statement Block. So the above example for code generation doesn’t work as Visual Studio complains about various issues with the syntax.
Thoughts?
If the types are in the assembly you are building you can use
I used this trick in my View Gen T4 templates for Code First