In many cases, I want to do some filtering (and sometimes projection) on the server side and then switch to client-side for operations that the LINQ provider doesn’t natively support.
The naive approach (which is basically what I do now) is to just break it up into multiple queries, similar to:
var fromServer = from t in context.Table
where t.Col1 = 123
where t.Col2 = "blah"
select t;
var clientSide = from t in fromServer.AsEnumerable()
where t.Col3.Split('/').Last() == "whatever"
select t.Col4;
However, there are many times where this is more code/trouble than it’s really worth. I’d really like to do a ‘switch to client side’ in the middle. I’ve tried various methods of using a query continuation, but after doing a ‘select t into foo’ at the end of the first query, foo is still an individual item, not the collection, so I can’t AsEnumerable() it.
My goal is to be able write something more like:
var results = from t in context.Table
where t.Col1 = 123
where t.Col2 = "blah"
// Magic happens here to switch to the client side
where t.Col3.Split('/').Last() == "whatever"
select t.Col4;
Okay, firstly you absolutely should not use the code here. It was written by trained stunt-hamsters who have been trained not to throw up when dealing with this code of this nature.
You should absolutely pick one of the options you know about:
IEnumerable<T>then you don’t need the call toAsEnumerable– that won’t work if you’ve got an anonymous type as the element type of course)AsEnumerableAsEnumerablecall fit in.However, you can do a bit of magic, using the way that query expressions are translated. You just need to make one of the standard query operators with a representation in query expressions have a different translation. The simplest option here is probably “Where”. Just write your own extension method taking an
IQueryable<T>and aFunc<T, SomeType>whereSomeTypeisn’tbool, and you’re away. Here’s an example, first of the hack itself and then a sample use of it…