1

I have a LINQ query which works fine when I test it in LINQPad agains my SQL Server database, however when I test it against my Entity Framework context (which is required in my LightSwitch .NET app) it gives an error that .First() must be user as a final operation.

Table.Where(re => !re.UserSave.HasValue || re.UserSave == INT PARAMETER)
     .GroupBy(re => re.UniqueKey)
     .Select(g => g.FirstOrDefault(x => x.UserSave.HasValue) ?? g.First())

It suggest that using FirstOrDefault() instead, but since i call First() only if FirstOrDefault() returns false I have no idea how to get around this problem.

NotSupportedException: The method 'First' can only be used as a final query operation. Consider using the method 'FirstOrDefault' in this instance instead.

Thanks for any help!

1 Answer 1

2

Change your query to use FirstOrDefault instead of First:

Table.Where(re => !re.UserSave.HasValue || re.UserSave == INT PARAMETER)
     .GroupBy(re => re.UniqueKey)
     .Select(g => g.FirstOrDefault(x => x.UserSave.HasValue) ?? g.FirstOrDefault())
2
  • That totally works, thanks! Why didn't i try that, I feel stupid. Still, it makes no sense at all why First() wouldn't work.. Apr 19, 2013 at 10:38
  • Because First requires an exception when no results were fetched. Apr 19, 2013 at 10:40

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.