我正在使用 PredicateBuilder构建可重用的表达式作为对象的返回值。例如:
public interface ISurveyEligibilityCriteria
{
Expression<Func<Client, bool>> GetEligibilityExpression();
}
我想进行自动化测试,以确定特定表达式是否可由 Entity Framework 转换为 T-SQL(即它在“执行”时不会抛出 NotSupportedException
)。我在互联网上找不到任何东西 - 这可能吗(似乎应该是)?
最佳答案
您可以创建一个包含表达式的 LINQ 语句,然后在不实际执行它的情况下检查它是否可以被翻译:
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");
}
在 Assert
中,您可以测试任何您希望成为生成的 SQL 字符串的一部分的内容,但当然,如果无法翻译表达式,测试将失败,因为例如抛出 NotSupportedException
。
你可以把它包装成一个方便的扩展方法:
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();
}
}
然后在你的测试中:
// act
Action act = () => context.CompilePredicate(predicate);
// assert
act.ShouldNotThrow();
关于c# - 表达式翻译的自动化测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29252113/