Handling 'Sequence has no elements' Exception

.net ado.net c# entity-framework linq

Question

When I try to change a quantity in my cart, a Sequence has no elements issue is raised.

And I'm not even sure what it implies. I first believed that maybe a null value was being given someplace, however I have confirmed that:

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:

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 suggestions as to what may be causing this?

1
44
8/3/2012 7:03:12 PM

Accepted Answer

First() If your select returns 0 rows, this is the cause. That exception has to be caught, or you should useFirstOrDefault() which, in the absence of any items, will return null.

92
6/23/2014 4:32:28 PM

Popular Answer

You are using the First() function of linq, which according to the documents throws an InvalidOperationException if it is used on an empty collection.

You should probably use FirstOrDefault(), which will return null if the collection is empty instead of raising an exception, if you anticipate your query's output to sometimes be empty.



Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow