wali ahmad wali ahmad - 27 days ago 13
ASP.NET (C#) Question

if statement is not working inside controller mvc 5 asp.net

this is the controller:

int id = 1;
var book = db.books.Where(r => r.bookid == id).First();
string onebook = book.bookid.ToString();
if(onebook != null)
{
return Content(onebook);
}else
{
return Content("Noting");
}


if there is value id(inside database) it will result and show the value

but if there is invalid value or null I don't get custom error but instead I get the err:


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

Answer

Use FirstOrDefault instead of First, It returns default value if the sequence contains no elements.:

var book = db.books.Where(r => r.bookid == id).FirstOrDefault();

Or even simpler:

var book = db.books.FirstOrDefault(r => r.bookid == id);
Comments