This does this due to the expected behavior of FirstOrDefault()
. Calling FirstOrDefault()
on an empty JobProviderJobs set will result in a null
value, but calling it on an empty int
set will result in 0
. Recognizing this, LINQ to Entities tries to call the case statement at the end of the query to ensure that if there are no matching JobProviderJobs, the result of the selection will be 0 instead of null.
In most cases, recreating the inner projection will not cause problems, but using NewGuid()
explicitly excludes this logic.
You have found one solution. Another would be to make the result of an internal expression this way:
from jpj in JobProviderJobs where jpj.JobID == 4725 && jpj.JobProviderID == (from jp2 in JobProviderJobs where jp2.JobID == 4725 orderby Guid.NewGuid() select (int?) jp2.JobProviderID).FirstOrDefault() select new { JobProviderID = jpj.JobProviderID }
A more correct implementation will repeat the use of the original SQL projection instead of creating two equivalent forecasts. The parser is probably just not complex enough to handle this properly, and developers have never seen the need to fix it because SQL Server should be able to optimize identical forecasts, provided that they are deterministic.
You should probably register a bug report if it does not already exist.
source share