gpt4 book ai didi

entity-framework - 防止 T4 模板删除现有文件

转载 作者:行者123 更新时间:2023-12-03 07:35:34 25 4
gpt4 key购买 nike

我想为 edmx 模型中的每个实体创建一个名为 {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);

#>

最佳答案

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

戴恩·莫格里奇想出了一个聪明的方法来做到这一点。他检查该文件是否已经存在。如果是的话,他将其读入并按原样写回。如果没有,他将渲染他的模板。查看 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"));
}

关于entity-framework - 防止 T4 模板删除现有文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5940372/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com