You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

.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 an IEnumerable<IPublishedContent> that uses deferred execution. That means the actual XPath query and creation of your Event objects doesn't happen until you start enumerating the collection (like when you call Count(), 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.12 05:29:41