【问题标题】:"Sequence contains no elements" when using .Any()使用 .Any() 时“序列不包含任何元素”
【发布时间】:2015-01-03 02:49:58
【问题描述】:

这似乎是一个直截了当的问题。我开始怀疑剃须刀有错误。

if (Model.athleteImages .Any()){
//some code

}

我已将以上内容替换为以下内容:

    if (Model.athleteImages.Count > 0)
    {
        var i = 0;
        <li data-target="#carousel-example-generic" data-slide-to="0" class="active"></li>
        while (i + 1 < Model.athleteImages.Count())
        {
            i++;
            <li data-target="#carousel-example-generic" data-slide-to="@i"></li>

        }
    }

对于没有元素的集合,这总是抛出“序列不包含元素”,例如计数() = 0。

Any() 应该测试序列是否包含元素。这就是它的全部目的。

我也试过了

if (Model.athleteImages.FirstOrDefault().[fieldName] != null){
//some code

}

同样的结果。

这里有一些来自控制器的相关代码,供那些想知道图像集合是什么的人使用

var adImages = from i in db.athleteImages
    where thisAd.albumId == i.albumId
    where i.deleted == false
    select i;

viewModel.athleteImages = athleteImages.ToList();

这是视图模型类

public class ListingViewModel
{
    public site site { get; set; }
    public userAd userAd { get; set; }
    public List<athleteImage> athleteImages { get; set; }
    public string categoryName { get; set; }
    public int categoryId { get; set; }
    public string subcategoryName { get; set; }
    public int subcategoryId { get; set; }
}

堆栈跟踪

[InvalidOperationException: Sequence contains no elements]
   System.Linq.Enumerable.First(IEnumerable`1 source) +269
   ASP._Page_Views_userAds_Listing_cshtml.Execute() in c:\Users\Bill\Documents\Visual Studio 2013\Projects\CuriousMarketplaces\CuriousMarketplaces\Views\userAds\Listing.cshtml:32
   System.Web.WebPages.WebPageBase.ExecutePageHierarchy() +198
   System.Web.Mvc.WebViewPage.ExecutePageHierarchy() +105
   System.Web.WebPages.StartPage.RunPage() +17
   System.Web.WebPages.StartPage.ExecutePageHierarchy() +64
   System.Web.WebPages.WebPageBase.ExecutePageHierarchy(WebPageContext pageContext, TextWriter writer, WebPageRenderingBase startPage) +78
   System.Web.Mvc.RazorView.RenderView(ViewContext viewContext, TextWriter writer, Object instance) +235
   System.Web.Mvc.BuildManagerCompiledView.Render(ViewContext viewContext, TextWriter writer) +107
   System.Web.Mvc.ViewResultBase.ExecuteResult(ControllerContext context) +291
   System.Web.Mvc.ControllerActionInvoker.InvokeActionResult(ControllerContext controllerContext, ActionResult actionResult) +13
   System.Web.Mvc.ControllerActionInvoker.InvokeActionResultFilterRecursive(IList`1 filters, Int32 filterIndex, ResultExecutingContext preContext, ControllerContext controllerContext, ActionResult actionResult) +56
   System.Web.Mvc.ControllerActionInvoker.InvokeActionResultFilterRecursive(IList`1 filters, Int32 filterIndex, ResultExecutingContext preContext, ControllerContext controllerContext, ActionResult actionResult) +420
   System.Web.Mvc.ControllerActionInvoker.InvokeActionResultWithFilters(ControllerContext controllerContext, IList`1 filters, ActionResult actionResult) +52
   System.Web.Mvc.Async.<>c__DisplayClass2b.<BeginInvokeAction>b__1c() +173
   System.Web.Mvc.Async.<>c__DisplayClass21.<BeginInvokeAction>b__1e(IAsyncResult asyncResult) +100
   System.Web.Mvc.Async.WrappedAsyncResult`1.CallEndDelegate(IAsyncResult asyncResult) +10
   System.Web.Mvc.Async.WrappedAsyncResultBase`1.End() +49
   System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeAction(IAsyncResult asyncResult) +27
   System.Web.Mvc.Controller.<BeginExecuteCore>b__1d(IAsyncResult asyncResult, ExecuteCoreState innerState) +13
   System.Web.Mvc.Async.WrappedAsyncVoid`1.CallEndDelegate(IAsyncResult asyncResult) +36
   System.Web.Mvc.Async.WrappedAsyncResultBase`1.End() +54
   System.Web.Mvc.Controller.EndExecuteCore(IAsyncResult asyncResult) +39
   System.Web.Mvc.Controller.<BeginExecute>b__15(IAsyncResult asyncResult, Controller controller) +12
   System.Web.Mvc.Async.WrappedAsyncVoid`1.CallEndDelegate(IAsyncResult asyncResult) +28
   System.Web.Mvc.Async.WrappedAsyncResultBase`1.End() +54
   System.Web.Mvc.Controller.EndExecute(IAsyncResult asyncResult) +29
   System.Web.Mvc.Controller.System.Web.Mvc.Async.IAsyncController.EndExecute(IAsyncResult asyncResult) +10
   System.Web.Mvc.MvcHandler.<BeginProcessRequest>b__5(IAsyncResult asyncResult, ProcessRequestState innerState) +21
   System.Web.Mvc.Async.WrappedAsyncVoid`1.CallEndDelegate(IAsyncResult asyncResult) +36
   System.Web.Mvc.Async.WrappedAsyncResultBase`1.End() +54
   System.Web.Mvc.MvcHandler.EndProcessRequest(IAsyncResult asyncResult) +31
   System.Web.Mvc.MvcHandler.System.Web.IHttpAsyncHandler.EndProcessRequest(IAsyncResult result) +9
   System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +9651116
   System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +155

【问题讨论】:

  • 那么,Model.Images 是什么类型?它从何而来?你首先如何填充Model.Images
  • 需要更多信息,因为这不应该发生。顺便说一句,Model.Images.FirstOrDefault().[fieldName]NullReferenceException 的必经之路。
  • 请检查您的代码以查找使用Single()First() 的地方。这些似乎是导致此错误的主要原因,如果您发布的第一行确实触发了异常,那么您的 .Images 属性可能正在调用其中一个方法作为副作用?
  • @JLRishe 谢谢,我已经检查过了,但我没有在图像集合上使用 Single 或 First。
  • @BillHarris 你能告诉我们if块里面有什么吗?

标签: asp.net-mvc razor


【解决方案1】:

如果您真正关心的是集合中是否有任何图像,那么这样的事情可能更有意义:

if (Model.Images.Count > 0) {

}

【讨论】:

  • 那是我尝试的第一个瘦身。不幸的是,它产生了相同的结果。
【解决方案2】:

如果源为空,Any() 将抛出异常,这是记录在案的行为以及它应该如何工作:http://msdn.microsoft.com/en-us/library/vstudio/bb534972%28v=vs.100%29.aspx

Dave 的解决方案很好,但我会添加一个空检查,如果对象为空,Count 也会抛出异常。

if(Model.Images != null && Model.Images.Count > 0) {

}

【讨论】:

  • 所以在这种情况下它会抛出ArgumentNullException。这不是 OP 报告的内容。
  • @spender 显然我应该读得更好。我无法复制相同的行为,只是在 MVC razor 中创建了一个带有基类的测试项目。它要么在 Sequence 为空时抛出 ArgumentNullexception,要么在计数为 0 时正常工作。OP 你模型上的 Images 字段到底是什么?
  • 是的。我也看不出这是怎么回事。 OP 需要提供更多信息。
  • 感谢大家的及时关注。 Model.Images 来自 ViewModel。 Images 集合是 Image 类型的 IEnumerable。 Image 类是我的模型文件夹中的 POCO 类。我试过测试null。我需要一种万无一失的测试方法来查看该集合是否包含任何元素。 Any() 根据定义应该这样做(至少这是智能感知所声称的)。我也试过计数。
  • 我应该补充一点,如果图像中有一个图像对象,代码运行良好。再次感谢大家。
【解决方案3】:

Dan 给了我需要的提示。

即使调试器指示错误发生在我的 if 块的关闭块中,但事实并非如此。

在同一视图中的稍后代码块中,我有这个:

<div class="item active" id="0">
    <div style="width:400px;height:300px;text-align:center;background-color:black;">
        <img src="/Content/Images/Deals/1/@Model.athleteImages.First().fullImage" style="height:300px;" alt="...">
        <div class="carousel-caption">
            some caption
        </div>
    </div>
</div>

要解决这个问题,我需要再次测试。所以:

if (Model.athleteImages.Count > 0) 
{
<div class="item active" id="0">
    <div style="width:400px;height:300px;text-align:center;background-color:black;">
        <img src="/Content/Images/Deals/1/@Model.athleteImages.First().fullImage" style="height:300px;" alt="...">
        <div class="carousel-caption">
            some caption
        </div>
    </div>
</div>
}

让我大吃一惊的是,错误消息表明第 32 行有问题。实际上它在第 37 行。

【讨论】:

  • 现在说得通了,并确认堆栈跟踪中的第二行 ((System.Linq.Enumerable.First(IEnumerable`1 source) +269)) 如果您有优化代码检查
猜你喜欢
  • 1970-01-01
  • 2015-09-04
  • 2021-04-26
  • 2015-02-19
  • 1970-01-01
  • 2016-12-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多