防止T4模板删除现有文件

Har*_*ryK 6 t4 entity-framework

我想为我的edmx-model中的每个实体创建一个名为{0} Validator.cs的独立类文件(现在不关心它的内容).

这似乎有效,但我无法解决阻止我的T4模板首先删除我的所有文件.我怎样才能摆脱这种行为?

我发现如果我调用fileManager.Process(true),我的validator.tt文件下的所有文件都将被重新创建(我不想这样).

有什么想法吗?谢谢!

<#@ template language="C#" debug="false" hostspecific="true"#>
//<#@ include file="EF.Utility.CS.ttinclude"#>
<#@output extension=".cs"#>

<#
CodeGenerationTools code = new CodeGenerationTools(this);
MetadataLoader loader = new MetadataLoader(this);
CodeRegion region = new CodeRegion(this, 1);

string inputFile =@"ServicesEntities.edmx";
EdmItemCollection ItemCollection = loader.CreateEdmItemCollection(inputFile);
string namespaceName = code.VsNamespaceSuggestion();

EntityFrameworkTemplateFileManager fileManager = EntityFrameworkTemplateFileManager.Create(this);

// for test purposes only...
fileManager.Process(true);

// for each entity, create a xxxValidator.cs file

foreach (EntityType entity in ItemCollection.GetItems<EntityType>().OrderBy(e => e.Name))
{
     string fileName = entity.Name + "Validator.cs";
     string filePath = this.Host.TemplateFile.Substring(0,this.Host.TemplateFile.LastIndexOf(@"\")); 
     filePath = filePath + @"\" + fileName;

     if(!File.Exists(filePath)) 
     {
          fileManager.StartNewFile(filePath);

#>
// the content of the validator class
public partial class <#=code.Escape(entity)#>
{
    public bool ValidateModel()
    {
    // enter checkmethods here!!! again
    return true;
    }
}
<#          
    }           
}

fileManager.Process(true);

#>
Run Code Online (Sandbox Code Playgroud)

小智 5

我处于完全相同的情况.我想为数据注释生成好友类.我不想将数据放入edmx文件并更改我的模板以根据edmx数据添加正确的注释.这将花费太长时间.最简单的解决方案是生成一个伙伴类并设置它,使其不会每次都重新生成.在这种情况下,效率比应该始终重新生成T4类的约定更重要.

Dane Morgridge想出了一个聪明的方法来做到这一点.他检查文件是否已经存在.如果确实如此,他会将其读入并按原样将其写回.如果没有,他会渲染他的模板.查看DbContext Templates\IRepository.tt. https://github.com/danemorgridge/efrepo

以下是相关章节.

string OutputFile(string filename)
{
    using(StreamReader sr = new StreamReader(Path.Combine(GetCurrentDirectory(),filename)))
    {
        string contents = sr.ReadToEnd();
        return contents;
    }
}

if(!DoesFileExist(entity.Name + "Repository.cs"))
{
    fileManager.StartNewFile(entity.Name + "Repository.cs");
}
else
{
    fileManager.StartNewFile(entity.Name + "Repository.cs");
    this.Write(OutputFile(entity.Name + "Repository.cs"));
}
Run Code Online (Sandbox Code Playgroud)


sra*_*sra 1

不,你不能。T4 模板每次被触发时都会生成代码并执行代码。在此之前,所有文件都会被删除。但你有什么问题吗?您的自定义代码应该放置在部分代码中,因此即使重新生成其他部分代码也没关系。