[c#] Why is this error, 'Sequence contains no elements', happening?

I am getting an Invalid Operation Exception, the stack is down below. I think it is because db.Responses.Where(y => y.ResponseId.Equals(item.ResponseId)).First(); is not returning any results. I checked the response data and the userResponseDetails has a ResponseId, I also just used a hard coded value. I also know that the statement that calls this one is adding the Responses row that this function should be calling. (This was working about a month ago and I don't remember changing anything that would break this)

[InvalidOperationException: Sequence contains no elements]
   System.Linq.Enumerable.First(IEnumerable`1 source) +269
   System.Data.Objects.ELinq.ObjectQueryProvider.<GetElementFunction>b__0(IEnumerable`1 sequence) +41
   System.Data.Objects.ELinq.ObjectQueryProvider.ExecuteSingle(IEnumerable`1 query, Expression queryRoot) +59
   System.Data.Objects.ELinq.ObjectQueryProvider.System.Linq.IQueryProvider.Execute(Expression expression) +133
   System.Data.Entity.Internal.Linq.DbQueryProvider.Execute(Expression expression) +87
   System.Linq.Queryable.First(IQueryable`1 source) +251
   InSight.Controllers.ForecasterController.userResponseDetails(List`1 userResponseDetails) +1039

Here is the offending code.

    [HttpPost]
    public JsonResult userResponseDetails(List<ResponseDetailsPartial> userResponseDetails)
    {

        foreach (ResponseDetailsPartial item in userResponseDetails)
        {
            ResponseDetails temp = new ResponseDetails();
            temp.ResponseId = item.ResponseId;
            temp.ResponseDetailVal = item.ResponseDetailVal;
            temp.QuestioChoicesId = item.QuestioChoicesId;
            temp.Response = db.Responses
                  .Where(y => y.ResponseId.Equals(item.ResponseId)).First();
            temp.QuestionChoice = db.QuestionChoices
                   .Where(x => x.QuestionChoicesId.Equals(item.QuestioChoicesId)).First();
          db.ResponseDetails.Add(temp);
        }
        db.SaveChanges();

        return Json(new { ResponseDetailsId = userResponseDetails }, JsonRequestBehavior.AllowGet);
    }

This is the AJAX that calls this specific action:

$.ajax({
         type: "POST",
         url: '/Forecaster/userResponseDetails/',
         data: JSON.stringify(rdetail),
         dataType: 'json',
         contentType: 'application/json',
     })

and this is rdetail after it has been strigified:

[{"ResponseId":118,"ResponseDetailVal":0.36,"QuestioChoicesId":null}] 

This question is related to c# asp.net-mvc-3 linq

The answer is


If this is the offending line:

db.Responses.Where(y => y.ResponseId.Equals(item.ResponseId)).First();

Then it's because there is no object in Responses for which the ResponseId == item.ResponseId, and you can't get the First() record if there are no matches.

Try this instead:

var response
  = db.Responses.Where(y => y.ResponseId.Equals(item.ResponseId)).FirstOrDefault();

if (response != null)
{
    // take some alternative action
}
else
    temp.Response = response;

The FirstOrDefault() extension returns an objects default value if no match is found. For most objects (other than primitive types), this is null.


In the following line.

temp.Response = db.Responses.Where(y => y.ResponseId.Equals(item.ResponseId)).First();

You are calling First but the collection returned from db.Responses.Where is empty.


Examples related to c#

How can I convert this one line of ActionScript to C#? Microsoft Advertising SDK doesn't deliverer ads How to use a global array in C#? How to correctly write async method? C# - insert values from file into two arrays Uploading into folder in FTP? Are these methods thread safe? dotnet ef not found in .NET Core 3 HTTP Error 500.30 - ANCM In-Process Start Failure Best way to "push" into C# array

Examples related to asp.net-mvc-3

Better solution without exluding fields from Binding IIs Error: Application Codebehind=“Global.asax.cs” Inherits=“nadeem.MvcApplication” Can we pass model as a parameter in RedirectToAction? return error message with actionResult Why is this error, 'Sequence contains no elements', happening? Failed to load resource: the server responded with a status of 500 (Internal Server Error) in Bind function 500.19 - Internal Server Error - The requested page cannot be accessed because the related configuration data for the page is invalid String MinLength and MaxLength validation don't work (asp.net mvc) How to set the value of a hidden field from a controller in mvc How to set a CheckBox by default Checked in ASP.Net MVC

Examples related to linq

Async await in linq select How to resolve Value cannot be null. Parameter name: source in linq? What does Include() do in LINQ? Selecting multiple columns with linq query and lambda expression System.Collections.Generic.List does not contain a definition for 'Select' lambda expression join multiple tables with select and where clause LINQ select one field from list of DTO objects to array The model backing the 'ApplicationDbContext' context has changed since the database was created Check if two lists are equal Why is this error, 'Sequence contains no elements', happening?