处理“序列没有元素"异常 [英] Handling 'Sequence has no elements' Exception

查看:105
本文介绍了处理“序列没有元素"异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在更新购物车中的数量,但它抛出的序列没有元素异常.

I am updating a quantity in my cart, but it is throwing a Sequence has no elements' exception.

我什至不知道那意味着什么.起初我以为可能是某个地方传递了一个空值,但事实并非如此,因为我已经检查过:

And I don't know what that even means. At first I thought that maybe there was a null value being passed somewhere, but that isn't the case, as I've checked that:

序列不包含任何元素说明:未处理的异常 在执行当前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.

异常详细信息:System.InvalidOperationException:序列 不包含任何元素

Exception Details: System.InvalidOperationException: Sequence contains no elements

源错误:

第35行:var uid = WebSecurity.CurrentUserId;第36行: var newqty = Request.Form ["Quantity"];第37行:
OModel.Cart c =(来自数据库中的项目.第38行:
其中item.UserId == uid&& item.PartNumber == pnumber&& item.OrderId == oid第39行:选择项).First();

Line 35: var uid = WebSecurity.CurrentUserId; Line 36: var newqty = Request.Form["Quantity"]; Line 37:
OModel.Cart c = (from item in database.Carts Line 38:
where item.UserId == uid && item.PartNumber == pnumber && item.OrderId == oid Line 39: select item).First();

有什么想法会导致这种情况吗?

Any ideas what could be causing this?

推荐答案

First()会导致此问题.您要么必须捕获该异常,要么使用FirstOrDefault(),如果没有任何元素,它将返回null.

First() is causing this if your select returns 0 rows. You either have to catch that exception, or use FirstOrDefault() which will return null in case of no elements.

这篇关于处理“序列没有元素"异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆