T4代码生成脚本从添加注释,添加命名空间开始(一款强大的代码生成工具从看懂脚本,到随心所欲的玩弄代码,本文只是T4的冰山一角,博主将不断深入探索并完善该文章)

  1. 精通T4脚本要从读懂脚本的关键代码片段开始

 1.1. 给类添加注释-->看懂类对应的代码:<#=codeStringGenerator.EntityClassOpening(entity)#>

替换前
WriteHeader(codeStringGenerator, fileManager);
XXXXXXXXXXXXXXXXXXXXXXXXXXXXX
<#=codeStringGenerator.EntityClassOpening(entity)#>
替换后

WriteHeader(codeStringGenerator, fileManager);

string summary=string.Empty;
foreach (var entity in typeMapper.GetItemsToGenerate<EntityType>(itemCollection))
{
fileManager.StartNewFile(entity.Name + ".cs");
BeginNamespace(code);
if(entity.Documentation !=null && entity.Documentation.Summary!=null)
summary=entity.Documentation.Summary;
else
summary=entity.Name;
#>
<#=codeStringGenerator.UsingDirectives(inHeader: false)#>
/// <summary>
/// <#=summary#>
/// </summary>
<#=codeStringGenerator.EntityClassOpening(entity)#>

1.2. 给命名空间添加注释-->看懂引用的命名空间对应的代码:<#=codeStringGenerator.UsingDirectives(inHeader: false)#>

该方法实现与于odeStringGenerator类下边。代码如下:

  public string UsingDirectives(bool inHeader, bool includeCollections = true)
{
return inHeader == string.IsNullOrEmpty(_code.VsNamespaceSuggestion())
? string.Format(
CultureInfo.InvariantCulture,
"{0}using System;{1}" +
"{2}"+"{3}",
inHeader ? Environment.NewLine : "",
includeCollections ? (Environment.NewLine + "using System.Collections.Generic;") : "",
includeCollections ? (Environment.NewLine + "using System.Data;") : "",
inHeader ? "" : Environment.NewLine)
: "";
}

1.3. 给属性添加注释-->看懂属性的代码对应的代码:<#=codeStringGenerator.Property(edmProperty)#>

替换前:

        foreach (var edmProperty in simpleProperties)
{
#>
<#=codeStringGenerator.Property(edmProperty)#>

替换后:

foreach (var edmProperty in simpleProperties)
{
if (edmProperty.Documentation != null && edmProperty.Documentation.Summary != null)
{
summary=edmProperty.Documentation.Summary;
}
else
{
summary="";
}
#>
/// <summary>
/// <#=summary#>
/// </summary>
<#=codeStringGenerator.Property(edmProperty)#>

1.4. 看懂命名空间namespace对应的代码:namespace <#=code.EscapeNamespace(codeNamespace)#>

上一篇:Java数据库 高级查询


下一篇:SSM-Spring-19:Spring中JdbcTemplate