T4 PowerShell 数组序列化错误
Posted
技术标签:
【中文标题】T4 PowerShell 数组序列化错误【英文标题】:T4 PowerShell Array Serialization Error 【发布时间】:2013-08-08 03:08:58 【问题描述】:我正在使用 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 变量由于某种原因无法序列化。我做错了什么?
【问题讨论】:
【参考方案1】:我很久以前就试过了,但是没用:(
我还是解决了这个问题,因为我注意到您可以将一个字符串数组传递给 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;
<#
#>
不是我喜欢做的……但它有效
【讨论】:
以上是关于T4 PowerShell 数组序列化错误的主要内容,如果未能解决你的问题,请参考以下文章
PowerShell - ConvertFrom-Json 无法正确序列化具有混合属性的 JSON 项目数组 [重复]
Azure Service Fabric 从 Visual Studio 发布升级 - PowerShell 脚本错误
powershell 来自https://stackoverflow.com/questions/1862554/get-childitem-recurse-as-a-parameter-in-pow