【发布时间】:2013-03-26 13:03:21
【问题描述】:
我在这部分代码中遇到了堆栈溢出异常,这显然是因为 Customer 对象调用了一个 CustomerBackgroundLevel 对象列表,每个对象都创建一个新的 customer 对象。我正在尝试解决这个问题,任何帮助将不胜感激..
客户构造函数 -
public CustomerVO(Customer item)
{
CustomerID = item.CustomerID;
CustomerName = item.CustomerName;
ECNNumber = item.ECNNumber;
CustomerBackgroundLevels = item.CustomerBackgroundLevels.Select(c => new CustomerBackgroundLevelVO(c)).ToList();
}
客户背景层构造器 -
public CustomerBackgroundLevelVO(CustomerBackgroundLevel item)
{
CustomerBackgroundLevelID = item.CustomerBackgroundLevelID;
CustomerID = item.CustomerID;
BackgroundLevelID = item.BackgroundLevelID;
StartDate = item.StartDate;
EndDate = item.EndDate;
Customer = new CustomerVO(item.Customer);
BackgroundLevel = new BackgroundLevelVO(item.BackgroundLevel);
}
客户获取方法-
public CustomerVO GetByID(int id)
{
var item = repository.AsQueryable().Where(x => x.CustomerID == id).FirstOrDefault();
if (item == null)
return null;
return new CustomerVO(item);
}
【问题讨论】:
-
作为一种解决方案,也许为
CustomerBackgroundLevelVO添加一个构造函数重载,它采用CustomerVO。然后你可以直接将它分配给CustomerBackgroundLevelVO.Customer,而不是实例化一个新的。CustomerVO构造函数中的 Linq 调用将如下所示:CustomerBackgroundLevels = item.CustomerBackgroundLevels.Select(c => new CustomerBackgroundLevelVO(c, this)).ToList()这将避免无限循环。这只有在您 A) 想要重用相同的CustomerVO对象并且 B) 不介意传递未完全初始化的对象时才有意义。 -
或者更好的是,在它们的构造函数中抛弃所有这些连接/子对象构造,并将其委托给特定的
Factory或Builder对象来创建/连接这些对象for 完全避免所有嵌套/递归的相互依赖关系。
标签: c# asp.net linq-to-entities stack-overflow infinite-loop