使用SqlProvider类型提供程序,我正在尝试做一些事情,我递归地折叠一个'查询标准'列表,
type Criterion = {
Column : string
Operator : string
Value : string
}
这样表达式树只被编译成SQL一次,而且我没有多次访问数据库。我尝试了一些方法,其中最成功的方法是这样的
let rec eval (acc : IQueryable<SourceEntity> option) (qrys : Criterion list) =
match qrys with
|[] -> acc
|x :: xs -> let acc' = let op,valu = translateOpnValu x
match acc with
|Some acc' -> query {
for elem in acc' do
where (elem.GetColumn x.Column op valu)
select elem
} |> Some
|None -> query {
for elem in ctx.Dbo.Source do
where (elem.GetColumn x.Column op valu)
select elem
} |> Some
eval acc' xs
函数translateOpnValu是
let translateOpnValu (c:Criterion) =
match c.Operator with
|"%=%" -> (=%), sprintf "%%%s%%" c.Value
|_ -> (=), c.Value
我得到了这个赘述
System.Exception: Unsupported expression. Ensure all server-side objects appear on the left hand side of predicates. The In and Not In operators only support the inline array syntax. InvokeFast(elem.GetColumn("Source Code"), value(FSI_0006+acc'@38-2), "%BEN%")
at Microsoft.FSharp.Linq.RuntimeHelpers.LeafExpressionConverter.EvaluateQuotation(FSharpExpr e)
at Microsoft.FSharp.Linq.QueryModule.EvalNonNestedInner(CanEliminate canElim, FSharpExpr queryProducingSequence)
at Microsoft.FSharp.Linq.QueryModule.EvalNonNestedOuter(CanEliminate canElim, FSharpExpr tm)
at Microsoft.FSharp.Linq.QueryModule.clo@1735-1.Microsoft-FSharp-Linq-ForwardDeclarations-IQueryMethods-Execute[a,b](FSharpExpr`1 )
at FSI_0006.evaluate(FSharpOption`1 acc, FSharpList`1 qrys) in F:\code_root\vs2015\F\CAMS\CAMS\scratch.fsx:line 47
at <StartupCode$FSI_0007>.$FSI_0007.main@() in F:\code_root\vs2015\F\CAMS\CAMS\scratch.fsx:line 60
如果我用translate隐式运算符(= / =%)替换translateOpnValu返回的'op',它可以正常工作。
我感觉这与被返回的运算符的类型被约束为(string - &gt; string - &gt; bool)的事实有关,而隐式运算符更通用。我怎样才能获得translateOpnValu函数来返回更多通用运算符?或许这根本不是问题......
答案 0 :(得分:3)
@Fyodor是正确的 - 为了让SQL提供程序正确地获取你的函数,你需要将它包装在一个引号中并将其拼接到查询表达式中。这样的事情应该有效:
let translateOpnValu (c:Criterion) =
match c.Operator with
|"%=%" -> <@ (=%) @>, sprintf "%%%s%%" c.Value
|_ -> <@ (=) @>, c.Value
// ...
query {
for elem in acc' do
where ((%op) (elem.GetColumn x.Column) valu)
select elem
}