Question: I am using [PredicateBuilder](http://www.albahari.com/nutshell/predicatebuilder.aspx) to build reusable expressions as return values of objects. For example:

```
public interface ISurveyEligibilityCriteria
{
    Expression<Func<Client, bool>> GetEligibilityExpression();
}

```

I want to have automated tests that determine whether a particular expression is translateable into T-SQL by Entity Framework (ie that it doesn't throw a `NotSupportedException` while "executing"). I can't find anything on the internet - is this possible (seems like it should be)?

Answer: 
You can create a LINQ statement containing the expression and then check whether it can be translated without actually executing it:

```
var connString = @"server=x;database=x";
using(var db = new MyContext(connString))
{
    // ToString() shows the generated SQL string.
    var sql = db.Entities.Where(generatedExpression).ToString();
    Assert.IsTrue(sql.StartsWith("SELECT");
}

```

In the `Assert` you can test anything you'd expect to be part of the generated SQL string, but of course if the expression can't be translated, the test will fail because e.g. a `NotSupportedException` is thrown.

---

You can wrap this up into a handy extension method:

```
public static class EntityFrameworkExtensions
{
    public static void CompilePredicate<T>(this DbContext context, Expression<Func<T, bool>> predicate)
        where T : class
    {
        context.Set<T>().Where(predicate).ToString();
    }
}

```

Then in your test:

```
// act
Action act = () => context.CompilePredicate(predicate);

// assert
act.ShouldNotThrow();

```
A very simple solution is executing it:

```
using (var context = ...)
{
    // The query will return null, but will be executed.
    context.Clients.Where(GetEligibilityExpression())
                   .Where(() => false)
                   .SingleOrDefault(); 
}

```

In older versions of EF (or using `ObjectContext`) you could have tried "manually" compiling the query with `CompiledQuery.Compile`, but this isn't supported with `DbContext`.