I am trying to do a simple EF 6.0 query, but it seems it am getting nowhere and banging my head with it.
I am querying to take a single row as an object, but this return two dimentional array like below;
[
[],
[],
[{
Id: 1,
Name: Abc
}]
]
What I would like to return is the object.
{
Id: 1,
Name: Abc
}
and here is the query
var q = _operatorAssessmentContext.OperatorAssessmentQuestions
.Select(x => x.ConditionalQuestions.Where(c => c.Id == questionId)).ToList();
So the whole idea is to change that two dimentional list into an object.
CodePudding user response:
First off, you say you want an object, but your variable, q, will be a list. I'm gonna assume you want an object, as that is what you stated.
Couple ways you can do this:
- You can flatten the list, and then take one.
- You can filter away empty lists in your list, and then take the first object of the first list in your list.
Personally, I would prefer the first, and the query going in to your variable, q, would look something like this:
var q = _operatorAssessmentContext
.OperatorAssessmentQuestions
.SelectMany(x => x.ConditionalQuestions.Where(c => c.Id == questionId))
.FirstOrDefault();
Note the only difference is me using .SelectMany(), which will take, as an input, a list of lists holding elements of some type, T, and return one list holding elements of the same type, T.