C# – entity framework – mscorlib.dll中发生未处理的“System.StackOverflowException”类型exception

mscorlib.dll中发生了未处理的“System.StackOverflowException”类型exception
确保没有无限循环或无限递归。

以下代码在此方法成功时调用:

internal static List GetProductsSoldByCompany(Guid CompanyID) { var ret = from a in _dbRiv.ProductsSold where a.Company.CompanyId == CompanyID select a; return ret.ToList(); } 

在返回时,它调用实体模型并尝试填充所有外键控对象(子对象)。 架构是[1公司有0到多个ProductsSold]。 出于某种原因,对以下代码的调用只会自行级联:

 [global::System.Data.Objects.DataClasses.EdmRelationshipNavigationPropertyAttribute("RIV_Model", "FK_ProductsSold_Company", "Company")] [global::System.Xml.Serialization.XmlIgnoreAttribute()] [global::System.Xml.Serialization.SoapIgnoreAttribute()] [global::System.Runtime.Serialization.DataMemberAttribute()] public Company Company { get { return ((global::System.Data.Objects.DataClasses.IEntityWithRelationships)(this)).RelationshipManager.GetRelatedReference("RIV_Model.FK_ProductsSold_Company", "Company").Value; } set { ((global::System.Data.Objects.DataClasses.IEntityWithRelationships)(this)).RelationshipManager.GetRelatedReference("RIV_Model.FK_ProductsSold_Company", "Company").Value = value; } } ///  /// There are no comments for Company in the schema. ///  [global::System.ComponentModel.BrowsableAttribute(false)] [global::System.Runtime.Serialization.DataMemberAttribute()] public global::System.Data.Objects.DataClasses.EntityReference CompanyReference { get { return ((global::System.Data.Objects.DataClasses.IEntityWithRelationships)(this)).RelationshipManager.GetRelatedReference("RIV_Model.FK_ProductsSold_Company", "Company"); } set { if ((value != null)) { ((global::System.Data.Objects.DataClasses.IEntityWithRelationships)(this)).RelationshipManager.InitializeRelatedReference("RIV_Model.FK_ProductsSold_Company", "Company", value); } } } 

如您所见,第一种方法调用第二种方法。 第二种方法似乎无休止地称自己为。

我如何解决这个问题?

在从头开始删除和重建我的模型3次后,堆栈溢出神奇地消失了。

将它归结为沿线的某个错误的向导错误。

试试这个:

 internal static List GetProductsSoldByCompany(Guid CompanyID) { var ret = from a in _dbRiv.Company where a.CompanyId == CompanyID select a.ProductsSolds; return ret.ToList(); } 

我使用Asp.net Mvc,Sql Server和Linq to Entities遇到了同样的问题。 通过callstack,我看到我的两个存储库在另一个存储库中都有一个新的存储库调用。 例…

Repository1.cs

 Respository2 repo2 = new Repository2(); 

Repository2.cs

 Repository1 repo1 = new Repository1(); 

我想这是一个愚蠢的错误,不完全确定最新情况(也许有人可以在这里说话……)除了显而易见的但是我把Repository调出来了,现在一切正常。

我认为您需要将公司 – >公司关系设置为延迟加载。

StackOverflow错误是由于无限循环而发生的,循环使用完整的高速缓存,然后在结束时显示堆栈溢出错误。

无限循环需要停止,并且调用相同的函数不是最佳实践。

优化代码并尽量避免循环。