【发布时间】:2010-09-19 07:18:27
【问题描述】:
编辑#2:问题解决了一半。往下看
作为后续问题,有没有人知道一种非侵入性的方法来解决我在下面尝试做的事情(即,在不触发无限循环的情况下将对象相互链接)?
我尝试创建一个 asp.net-mvc Web 应用程序,并得到一个 StackOverFlowException。控制器触发以下命令:
public ActionResult ShowCountry(int id)
{
Country country = _gameService.GetCountry(id);
return View(country);
}
GameService 是这样处理的(WithCountryId 是一个扩展):
public Country GetCountry(int id)
{
return _gameRepository.GetCountries().WithCountryId(id).SingleOrDefault();
}
GameRepository 像这样处理它:
public IQueryable<Country> GetCountries()
{
var countries = from c in _db.Countries
select new Country
{
Id = c.Id,
Name = c.Name,
ShortDescription = c.ShortDescription,
FlagImage = c.FlagImage,
Game = GetGames().Where(g => g.Id == c.GameId).SingleOrDefault(),
SubRegion = GetSubRegions().Where(sr => sr.Id == c.SubRegionId).SingleOrDefault(),
};
return countries;
}
GetGames() 方法导致 StackOverflowException:
public IQueryable<Game> GetGames()
{
var games = from g in _db.Games
select new Game
{
Id = g.Id,
Name = g.Name
};
return games;
}
我的业务对象与 linq2sql 类不同,这就是我用 select new 填充它们的原因。
在 mscorlib.dll 中发生了“System.StackOverflowException”类型的未处理异常
edit #1:我找到了罪魁祸首,它是以下方法,它触发了 GetCountries() 方法,该方法又触发了 GetSubRegions(),令人作呕:
public IQueryable<SubRegion> GetSubRegions()
{
return from sr in _db.SubRegions
select new SubRegion
{
Id = sr.Id,
Name = sr.Name,
ShortDescription = sr.ShortDescription,
Game = GetGames().Where(g => g.Id == sr.GameId).SingleOrDefault(),
Region = GetRegions().Where(r => r.Id == sr.RegionId).SingleOrDefault(),
Countries = new LazyList<Country>(GetCountries().Where(c => c.SubRegion.Id == sr.Id))
};
}
这里可能需要考虑其他事情 :) 当你因为喝了太多咖啡而以 OO 思维方式思考时会发生这种情况
【问题讨论】:
-
天啊,当我在首页看到这个问题时,我以为这个网站有问题。
-
+1 用于在 StackOverflow 上询问有关 StackOverflowExceptions 的问题
标签: asp.net-mvc linq stack-overflow