【问题标题】:Sequence contains no elements server side序列不包含任何元素服务器端
【发布时间】:2015-09-05 21:10:37
【问题描述】:

我正在开发一个 Asp.net MVC Web 应用程序,并且已经部署到 Web 服务器几个月了。就在最近,我遇到了一个让我感到困惑的新错误。发布我的应用程序并加载网站后,我收到以下错误消息:

 Sequence contains no elements

 Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code. 

 Exception Details: System.InvalidOperationException: Sequence contains no elements

 Source Error: 

An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below.

Stack Trace: 


[InvalidOperationException: Sequence contains no elements]
 System.Linq.Enumerable.First(IEnumerable`1 source) +514
System.Linq.Queryable.First(IQueryable`1 source) +330
LabSys.MvcApplication.Application_AuthorizeRequest(Object sender, EventArgs   e) +1261
  System.Web.SyncEventExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +92
 System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean&completedSynchronously) +165

我很困惑,因为应用程序在本地主机上完美运行,没有任何问题或错误消息。我还检查了我的数据库,它也已连接并验证到服务器。所以应该没有错误。

提前感谢您的帮助!

【问题讨论】:

  • 你的代码中哪里抛出了这个异常,你能显示一些代码吗?
  • 这是我坚持的部分。通过 localhost 查看网站时,不会在任何地方抛出该错误。一旦我通过发布的服务器查看它,它就会被扔到每一页上。
  • 此错误是否出现在您的应用程序的登录页面/主页上。如果我没记错的话,您正在那里查询数据库并且您没有检查返回的集合是否包含任何元素并且您正在使用它。

标签: c# asp.net-mvc database linq


【解决方案1】:

检查您的代码以确保使用 FirstOrDefault()SingleOrDefault() 而不是使用以下任何一种:First()Single()

当您收到 LINQ 错误“序列不包含元素”时,这是 通常是因为您使用的是 First() 或 Single() 命令而不是 比 FirstOrDefault() 和 SingleOrDefault()。

Sequence contains no elements?

【讨论】:

  • 非常感谢!我完全查看了 Global.asax.cs 文件中的一行代码,该文件在每个请求上都被调用,导致一个空值。
猜你喜欢
  • 2015-09-04
  • 2015-02-19
  • 1970-01-01
  • 2016-12-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-04-26
  • 2017-05-27
相关资源
最近更新 更多