Question

I am having trouble mixing c# functions with conditions in Linq-To-SQL

suppose i have a database table "things" and a local c# Function : bool isGood(thing, params)

I want to use that function to select rows from the table.

var bad = dataContext.Things.Where(t=>t.type=mytype && !isGood(t,myparams))
dataContect.Things.deleteAllOnSubmit(bad);

or

if (dataContext.Things.Any(t=>t.type=mytype && isGood(t,myparams)))
{
    return false;
}

Of course this does not work, Linq has no way of translating my function into a SQL statement. So this will produce:

NotSupportedException: Method 'Boolean isGood(thing,params)' has no supported translation to SQL.

What is the best way to redesign this so that it will work?

I can split the statements and convert to list like this:

List<Things> mythings dataContext.Things.Where(t=>t.type=mytype).toList()
if (mythings.Any(t=>isGood(t,myparams)))
{
    return false;
}

this works, but seems inefficient, since the whole list has to be generated in every case. And I don't think I can do a deleteAllOnSubmit with the result

I could do a foreach over mythings instead of calling toList(), that also works. Seems inelegant though.

What other options do I have, and what would be the recommended approach here?

edit:

calling asEnumerable() seems to be another option, and seems better than toList() at least. I.e.

dataContext.Things.Where(t=>t.type=mytype).asEnumerable().Any(t=>isGood(t,myparams))
Was it helpful?

Solution

Pulling the whole list back from the database to run a local c# function on it might seem inefficient, but that what you'd have to do if your isGood() function is local.

If you can translate your isGood() function into Linq, you could apply it before the toList() call, so it would get translated into SQL and the whole list wouldn't be retrieved.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top