这种错误是由于使用EF创建实体模型,并且模型间有关系并且添加了相应的导航属性,所以使用Json.Net(包括mvc自带的return Json()方法)转换类的实例的时候 把导航属性也算进去了(A是B的导航属性,B也是A的导航属性,所以会无限循环,导致Json会生成无数层),
解决办法是不要使用return Json()方法 使用Json.Net并且手动禁止Json对导航属性的转换:在实体模型类中添加using Newtonsoft.Json; 引用,在导航属性前加上特性标签 [JsonIgnore] Json.net就会忽略导航属性,由于模型类可能会经常重新生成,所以最好在模板文件(TT文件中修改以下内容)
public string UsingDirectives(bool inHeader, bool includeCollections = true)
{
return inHeader == string.IsNullOrEmpty(_code.VsNamespaceSuggestion())
? string.Format(
CultureInfo.InvariantCulture,
"{0}using System;\r\nusing Newtonsoft.Json;{1}" +//添加引用命名空间
"{2}",
inHeader ? Environment.NewLine : "",
includeCollections ? (Environment.NewLine + "using System.Collections.Generic;") : "",
inHeader ? "" : Environment.NewLine)
: "";
}
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
[JsonIgnore]//添加特性标签