0

我正在使用 T4Scaffolding 创建自定义脚手架。我使用以下 PS 代码获取项目中所有域对象的列表:

# List of all domain classes. Get all top level files/folders in the project | drill down to Models folder | Enumerate ProjectItems | Where Name ends with .cs | Select name truncating .cs, pluralized name
$domainClasses = (Get-Project "Domain").ProjectItems | Where { $_.Name -eq "Models" } | ForEach { $_.ProjectItems } | Where { $_.Name.EndsWith('.cs') } | Select @{ Name = 'Name'; Expression={ $_.Name.SubString(0,$_.Name.Length - 3) } }, @{ Name = 'Plural'; Expression={ Get-PluralizedWord $_.Name.SubString(0,$_.Name.Length - 3) } } 
if (!$domainClasses) { $domainClasses = @() }

然后我像这样调用 Add-ProjectItemViaTemplate 方法:

Add-ProjectItemViaTemplate $outputPath -Template MyTemplate `
  -Model @{ DomainClasses=[Array]$domainClasses } `
  -SuccessMessage "Added Domain output at {0}" `
  -TemplateFolders $TemplateFolders -Project $DomainProjectName -CodeLanguage $CodeLanguage -Force:$Force

运行 sacffold 时出现以下异常:

System.Runtime.Serialization.SerializationException: Type 'System.Management.Automation.PSCustomObject' in assembly 'System.Management.Automation, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35' is not marked as serializable.      

问题似乎是 $domainClasses 变量由于某种原因无法序列化。我究竟做错了什么?

4

1 回答 1

0

我很久以前试过这个,但它没有用:(

无论如何我都解决了,因为我注意到您可以将字符串数组传递给 T4 模板。因为你可以传入一个字符串数组,所以我用每个对象的信息构建了逗号分隔的字符串......然后我在 T4 模板中做了一个 split(",") 来取回数据......

例子

#Get regular properties
$properties = @()(Get-ProjectType $ModelType).Children | Where-Object{$_.Kind -eq 4 -and $_.Type.TypeKind -ne 1 } | ForEach{
$p = "$($_.Name),$($_.Type.AsString)"; 
$properties = $properties + $p
}

然后我只是将 $properties 数组作为常规参数(第四个参数)传递...

Add-ProjectItemViaTemplate $outputPath -Template ViewModel `
-Model @{   
Namespace = $namespace; 
DataType = [MarshalByRefObject]$foundModelType; 
DataTypeName = $foundModelType.Name; 
Properties = $properties;
Parents = $parents;
Children = $children;
ExtraUsings = $ximports
} `
-SuccessMessage "Added ViewModel for $ModelType {0}" `
-TemplateFolders $TemplateFolders -Project $coreProjectName -CodeLanguage $CodeLanguage -Force:$Force

在T4中我只是...

<#
//Own properties 
foreach (var property in Model.Properties) {
    var info = property.Split(',');
#>
    public <#= info[1] #> <#= info[0] #> {get;set;}
<#  
}
#>

不是我喜欢做的......但它有效

于 2013-08-25T18:17:57.627 回答