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}]
From "Fixing LINQ Error: Sequence contains no elements": When you get the LINQ error "Sequence contains no elements", this is usually because you are using the First() or Single() command rather than FirstOrDefault() and SingleOrDefault() .
Check again. Use debugger if must. My guess is that for some item in userResponseDetails this query finds no elements:
.Where(y => y.ResponseId.Equals(item.ResponseId))
so you can't call
.First()
on it. Maybe try
.FirstOrDefault()
if it solves the issue.
Do NOT return NULL value! This is purely so that you can see and diagnose where problem is. Handle these cases properly.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With