编辑:发生此错误的原因是在我的_Layout.cshtml中,我编写了一个链接,将此动作方法称为Html.Action()而不是Html.ActionLink()..
我正在使用EF6.1.3在MVC5中构建一个网站。 将Project的集合传递给视图时,我得到以下异常:
An unhandled exception of type 'System.StackOverflowException' occurred in mscorlib.dll
ActionMethod无限次被调用。
我四处搜索,似乎我在Json序列化程序中得到了一个参考循环。
所以我将[JsonIgnore]
添加到Project中具有对Project的引用的字段中。我还在Global.asax中添加了以下内容:
HttpConfiguration config = GlobalConfiguration.Configuration;
config.Formatters.JsonFormatter
.SerializerSettings
.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore;
仍然没有区别。 我还尝试将引用回Project的导航属性设置为null,仍然没有区别。这让我觉得可能还有别的事情发生了。
生成错误的代码:
public ActionResult Index()
{
return View(db.Projects.Include(p => p.ProjectMissingPeople).ToList());
}
Project.cs:
public class Project
{
public int ProjectID { get; set; }
public string ProjectName { get; set; }
public string ProjectDescription { get; set; }
public string ProjectImageUrl { get; set; }
[JsonIgnore]
public string FounderId { get; set; }
[ForeignKey("FounderId")]
[JsonIgnore]
public ApplicationUser Founder { get; set; }
public ICollection<ProjectMissingPeople> ProjectMissingPeople { get; set; }
}
ProjectMissingPeople.cs:
public class ProjectMissingPeople
{
public int ProjectMissingPeopleID { get; set; }
public string Text { get; set; }
public bool Open { get; set; }
[JsonIgnore]
public int ProjectID { get; set; }
[JsonIgnore]
public Project Project { get; set; }
}
Index.cshtml:
@model IEnumerable<ProjectStockholm.BusinessModels.Project>
@foreach(var project in Model)
{
@Html.Partial("_ProjectThumbnail", project)
}
ProjectThumbnail.cs:
@model ProjectStockholm.BusinessModels.Project
<div class="project-thumbnail">
<img url="@Model.ProjectImageUrl" />
<h2>@Model.ProjectName</h2>
<p>@Model.ProjectDescription</p>
<h4>Open positions</h4>
@foreach (var missingPeople in Model.ProjectMissingPeople)
{
<label>@missingPeople.Text</label>
<button class="btn btn-project-join-small">JOIN</button>
}
</div>
你知道如何帮助我吗?