通過T4模板解決EF模型序列號的循環引用問題
阿新 • • 發佈:2018-02-10
www ssm ould dir any mvc gen name post
在模型的T4模板(如model.tt)中插入如下代碼,這樣由模板生成的模型代碼中的導航屬性將自動帶有[JsonIgnore]標識,不會被序列化
1. 添加命名空間的引用
找到以下代碼,添加using Newtonsoft.Json;
BeginNamespace(code);
#>
using Newtonsoft.Json;
<#=codeStringGenerator.UsingDirectives(inHeader: false)#>
2.為導航屬性添加JsonIgnore標簽
找到以下代碼,插入[JsonIgnore]標簽
<#
foreach (var navigationProperty in navigationProperties)
{
if (navigationProperty.ToEndMember.RelationshipMultiplicity == RelationshipMultiplicity.Many)
{
#>
[JsonIgnore]
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
<#
}
#>
<#=codeStringGenerator.NavigationProperty(navigationProperty)#>
<#
}
}
#>
BTW:另外一個比較好的解決方是Gryzor大俠的:
解決.Net MVC EntityFramework Json 序列化循環引用問題.
通過T4模板解決EF模型序列號的循環引用問題