No translation to SQL

When you start to like LINQ (to SQL) very much, someday you may find yourself in a nasty situation when “LINQ cannot translate method to SQL” during … runtime. That’s sad but quite logical: LINQ maps the logic to equivalent SQL statement. If there is no equivalence, it won’t work. In other words:

var foo = my_context.my_table.Where(val => SuperComplexMethod(val));

won’t work.

The usual answer is to use Expression<Func> but it will only help if it is possible to do (like converting Math.Pow()).

Another option is to restructure your function and let it use the supported logic.

Sometimes, however, you are to lazy to do all of that just to call some arbitrary function. The solution? Just use the AsEnumerable(). It basically tells the LINQ: “Ok, you can’t do what I want using the underlying database, so leave it to me”. There might be some performance issues due to not being able to use the power of the database, but many time this is the easiest way to go.

var foo = my_context.my_table.AsEnumerable().Where(val => SuperComplexMethod(val));

Tags: , ,

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: