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();
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.
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.