I have a line of LINQ code that throws a System.NotSupportedException.
return unconvertedUrls
.Select(potentialQueryURL => ConvertPotentialQueryURLToSeed(potentialQueryURL))
.Where(id => id > 0)
.ToList();
The exception message is “Method ‘Int32 ConvertPotentialQueryURLToSeed(SeedsSQLConnector.PotentialQueryURL)’ has no supported translation to SQL”
However the simple conversion to a foreach loop runs with no problems.
var result = new List<int>();
foreach (var potentialQueryURL in unconvertedUrls)
{
var id = ConvertPotentialQueryURLToSeed(potentialQueryURL);
if (id > 0)
{
result.Add(id);
}
}
return result;
What’s going wrong and why?
========== EDIT ==========
Odd, a colleague suggested another fix that works too. It looks like the LINQ was passing ConvertPotentialQueryURLToSeed to the database! Anyway here’s the other fix, which is to add .ToList() to the previous statement:
var unconvertedUrls = (from url in _DataContext.PotentialQueryURLs
where !convertedUrlIds.Contains(url.Id)
select url).ToList();
return unconvertedUrls
.Select(potentialQueryURL => ConvertPotentialQueryURLToSeed(potentialQueryURL))
.Where(id => id > 0)
.ToList();
The reason is that LINQ to SQL doesn’t execute that code of the query but tries to convert it to an SQL statement. As it doesn’t know
ConvertPotentialQueryURLToSeedthis conversion failes.The foreach works because in that case the method
ConvertPotentialQueryURLToSeedis not used in the part of the LINQ query that is being translated to SQL.The version with
ToListworks for the same reason:ToListfetches the data from the query so far from the database. From that point onward, you are working on normal C# objects aka LINQ to Objects.