.NET 4.7.2下Umbraco 8中IEnumerable访问后清空问题求助
Hey there, I see exactly what's happening here—this is a classic gotcha with LINQ's deferred execution combined with how Umbraco handles XPath query results!
What's going wrong?
- The
Umbraco.ContentAtXPath(...)call returns anIEnumerable<IPublishedContent>that uses deferred execution. That means the actual XPath query and creation of yourEventobjects doesn't happen until you start enumerating the collection (like when you callCount(),Any(), or loop through it in your view). - Umbraco's XPath query results are designed to be enumerated only once. When you first call
model.Events.Count(), you're triggering that first enumeration which exhausts the query's result set. Any subsequent attempts to access the collection (like in your view) will find an empty set because the query can't be re-run to get fresh results.
The Fix: Force Immediate Execution
All you need to do is convert the deferred IEnumerable to an in-memory collection (like a List<Event>) using ToList()—this forces all the LINQ operations (filtering, sorting, taking top 3) to run immediately and store the results in memory. Then any subsequent calls to Count(), Any(), or looping through the collection will work as expected.
Here's your updated controller code:
public ActionResult RenderUpcoming() { UpcomingEventsModel model = new UpcomingEventsModel(); model.Title = "Upcoming Events"; // Add ToList() here to execute the query immediately and store results in memory model.Events = Umbraco.ContentAtXPath("root/homepage/events/event") .Select(x => new Event(x)) .Where(x => x.StartDate > DateTime.Now) .OrderBy(x => x.StartDate) .Take(3) .ToList(); model.TotalEvents = model.Events.Count(); // Now this works on the in-memory list model.EventListingLink = _kupoGeneralSettings.EventListingLink; return PartialView("~/Views/Partials/Events/UpcomingEvents.cshtml", model); }
A Quick Extra Note
This isn't unique to Umbraco—any time you're working with a deferred LINQ query that wraps a non-repeatable data source (like a database reader, or in this case Umbraco's XPath result enumerator), you'll run into this issue. Converting to a List or array ensures you're working with a static copy of the data in memory, avoiding the "empty collection" surprise.
内容的提问来源于stack exchange,提问作者0Neji

