webapi修改tt模板给字段添加JsonIgnore特性解决转换json循环引用问题

0.问题描述

EF生成的model带有导航属性,则json序列化会报循环引用错误,尝试如下

protected void Application_Start()
{
GlobalConfiguration.Configure(WebApiConfig.Register);

////config.Formatters.JsonFormatter.MediaTypeMappings.Add(new System.Net.Http.Formatting.QueryStringMapping("datatype", "json", "application/json"));/*http://www.cnblogs.com/mirrortom/p/5931573.html*/

GlobalConfiguration.Configuration.Formatters.XmlFormatter.SupportedMediaTypes.Clear();//清除xml序列化

//HttpConfiguration config = GlobalConfiguration.Configuration;
////config.Formatters.JsonFormatter.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore;
//config.Formatters.JsonFormatter.SerializerSettings.PreserveReferencesHandling = Newtonsoft.Json.PreserveReferencesHandling.Objects;

}

均无法解决.经搜索发现可以修改tt模板,给字段添加JsonIgnore特性

1.观察edmx生成的model字段

发现导航属性都是virtual,并且标记有特性[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]

2.修改tt模板,添加JsonIgnore特性

找到edmx文件下的.tt文件

搜索[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]

并在此行之上添加一行

[Newtonsoft.Json.JsonIgnore]

添加后

最终试验出需加载foreach里面if判断之前

<#
foreach (var navigationProperty in navigationProperties)
{
#>
[System.Xml.Serialization.XmlIgnore]
[Newtonsoft.Json.JsonIgnore]
<#
if (navigationProperty.ToEndMember.RelationshipMultiplicity == RelationshipMultiplicity.Many)
{
#>

3.项目添加NewtonSoftJson.dll的引用并编译

此时controller里直接返回db.Table1.ToList();不会发生循环引用

From:http://www.cnblogs.com/xuejianxiyang/p/6204111.html

原文地址:https://www.cnblogs.com/xuejianxiyang/p/6204111.html