Note that there are some explanatory texts on larger screens.

plurals
  1. POStackOverflowException caused by a linq query
    text
    copied!<p><strong>edit #2:</strong> Question solved halfways. Look below</p> <p>As a follow-up question, does anyone know of a non-intrusive way to solve what i'm trying to do below (namely, linking objects to each other without triggering infinite loops)?</p> <hr> <p>I try to create a asp.net-mvc web application, and get a StackOverFlowException. A controller triggers the following command:</p> <pre><code> public ActionResult ShowCountry(int id) { Country country = _gameService.GetCountry(id); return View(country); } </code></pre> <p>The GameService handles it like this (WithCountryId is an extension):</p> <pre><code> public Country GetCountry(int id) { return _gameRepository.GetCountries().WithCountryId(id).SingleOrDefault(); } </code></pre> <p>The GameRepository handles it like this:</p> <pre><code> public IQueryable&lt;Country&gt; 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 =&gt; g.Id == c.GameId).SingleOrDefault(), SubRegion = GetSubRegions().Where(sr =&gt; sr.Id == c.SubRegionId).SingleOrDefault(), }; return countries; } </code></pre> <p>The GetGames() method causes the StackOverflowException:</p> <pre><code> public IQueryable&lt;Game&gt; GetGames() { var games = from g in _db.Games select new Game { Id = g.Id, Name = g.Name }; return games; } </code></pre> <p>My Business objects are different from the linq2sql classes, that's why I fill them with a select new.</p> <p>An unhandled exception of type 'System.StackOverflowException' occurred in mscorlib.dll</p> <hr> <p><strong>edit #1:</strong> I have found the culprit, it's the following method, it triggers the GetCountries() method which in return triggers the GetSubRegions() again, ad nauseam:</p> <pre><code> public IQueryable&lt;SubRegion&gt; GetSubRegions() { return from sr in _db.SubRegions select new SubRegion { Id = sr.Id, Name = sr.Name, ShortDescription = sr.ShortDescription, Game = GetGames().Where(g =&gt; g.Id == sr.GameId).SingleOrDefault(), Region = GetRegions().Where(r =&gt; r.Id == sr.RegionId).SingleOrDefault(), Countries = new LazyList&lt;Country&gt;(GetCountries().Where(c =&gt; c.SubRegion.Id == sr.Id)) }; } </code></pre> <p>Might have to think of something else here :) That's what happens when you think in an OO mindset because of too much coffee</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload