Jax*_*ian 15 c# t4 visual-studio-2010
我有一个解决方案,其中包含一些项目.我想在我的一个测试项目中创建一些T4模板,以根据另一个项目中的代码生成测试.测试项目有一个项目参考另一个项目.我遇到的问题是我不知道如何获取我需要生成代码的edmx文件的文件路径.
示例(假装这是一个基于ASCII的解决方案资源管理器):
MySolution.sln
-> MyTests.csproj (C:\a\b\c\)
----> GeneratedTests.tt (C:\a\b\c\GeneratedTests.tt)
-> MyDAL.csproj (C:\x\y\z\)
----> MyModel.edmx (C:\x\y\z\MyModel.edmx)
Run Code Online (Sandbox Code Playgroud)
我的GeneratedTests.tt如何利用其项目引用获取MyModel.edmx的文件路径?
Mic*_*rry 15
此答案仅适用于Visual Studio.
设置T4模板的"hostspecific"属性.这使您可以访问Host属性.键入cast Host to IServiceProvider以调用GetService(typeof(DTE)).这使您可以遍历解决方案的内容.
<#@ template language="c#" hostspecific="true" #>
<#@ assembly name="EnvDTE" #>
<#@ import namespace="EnvDTE" #>
These are the projects in this solution:
<#
var serviceProvider = this.Host as IServiceProvider;
var dte = serviceProvider.GetService(typeof(DTE)) as DTE;
foreach (Project p in dte.Solution.Projects)
{
#>
<#=p.Name#> at <#=p.FullName#>
<#
}
#>
Run Code Online (Sandbox Code Playgroud)
另请参阅MSDN上的ITextTemplatingEngineHost接口和Oleg Synch的T4架构示例.
Aar*_*ton 11
基于James Close的评论,我能够编写以下模板来调试我的文件路径:
<#@ template language="C#" debug="true" hostspecific="true"#>
<#@ include file="EF.Utility.CS.ttinclude"#><#@
output extension=".txt"#><#
/////////Some standard-ish settings, continue reading on
CodeGenerationTools code = new CodeGenerationTools(this);
MetadataLoader loader = new MetadataLoader(this);
CodeRegion region = new CodeRegion(this, 1);
MetadataTools ef = new MetadataTools(this);
/////////Below are the relevant sections I used for debugging
string solutionsPath = Host.ResolveAssemblyReference("$(SolutionDir)");//Gives you the location of MySolution.sln
string edmxFile = solutionsPath + "MyDAL/MyDAL/MyModel.edmx"; //Note - VS projects usually have a subdir with the same name as the sln, hence the repetition for MyDAL
#>
Does this file exist?
<#
//
if (File.Exists(edmxFile))
{
//Continue.
#>
Yes
<#
}
else
{
#>
No
<#
}
#>
Run Code Online (Sandbox Code Playgroud)
这将生成一个.txt文件,并将非常快速地帮助您调试是否可以找到您的路径.
作为旁注,如果存在../App.config无法找到的相对目录路径(例如),我发现它有助于test1.txt在每个目录级别放置一个文件(例如),因为我发现它Host.ResolvePath不能使用我的设置查看当前程序集外部.这个警告会很快变得混乱,因为../../App.config可能会解决MySolution\App.config但../../MyDal/README.txt不会解决(因此找不到文件),即使这是正确的路径.就我所见,上面的代码似乎否定了这个问题.
上述解决方案也可能是解决此问题的方法 - 如何使用poco实体生成器
用这些线
string path = this.Host.ResolvePath("");
Directory.SetCurrentDirectory(path);
Run Code Online (Sandbox Code Playgroud)
然后使用相对路径获取您的edmx文件,例如,字符串inputFile = @“ .. \ Modal.edmx”;
这是行不通的。您必须通过路径引用 dll(您可以通过工具箱中的标记找到Host.ResolvePath并使用它VolatileAssembly,以便能够在不重新启动 VS 的情况下重新编译它)并使用反射来处理模型。
| 归档时间: |
|
| 查看次数: |
17905 次 |
| 最近记录: |