如何执行类似于SQL IN查询的查询表达式?
我正试图沿着这些方向做点什么:
let customerNumbers = set ["12345"; "23456"; "3456"]
let customerQuery = query {
for c in dataContext.Customers do
where(customerNumbers.Contains(c.CustomerNumber))
select c
}
但是我收到了一个错误:
System.NotSupportedException: Method 'Boolean Contains(System.String)' has no supported translation to SQL.
查看http://msdn.microsoft.com/en-us/library/hh225374.aspx处查询表达式的文档我应该对contains部分使用另一个查询,但是这段代码不起作用,示例已经破了:
// Select students where studentID is one of a given list.
let idQuery = query { for id in [1; 2; 5; 10] do select id }
query {
for student in db.Student do
where (idQuery.Contains(student.StudentID))
select student
}
idQuery确实不包含任何“包含”方法。
我也尝试过:
let customerNumbers = set ["12345"; "23456"; "3456"]
let customerQuery = query {
for c in dataContext.Customers do
where (query { for x in customerNumbers do exists (c.CustomerNumber=x)})
select r
}
但这会出现此错误消息:
System.NotSupportedException: Local sequence cannot be used in LINQ to SQL implementations of query operators except the Contains operator
我注意到经过一些测试后,除了Gene的建议之外,以下内容也可以正常使用:
let customerNumbers = set ["12345"; "23456"; "3456"]
query {
for customer in dataContext.Customer do
where (query { for x in customerNumbers do contains customer.CustomerNumber})
select customer
}
答案 0 :(得分:7)
我认为问题来自F#Set
实现方法Contains
的方式。它属于ICollection
接口,这个事实以某种方式扰乱了LINQ-to-SQL查询构建器。
如果您明确强制Contains
进入IEnumerable
领域的扩展方法,一切都会正常:
let customerNumbers = set ["12345"; "23456"; "3456"]
let customerQuery = query {
for c in dataContext.Customers do
where((customerNumbers :> IEnumerable<string>).Contains(c.CustomerNumber))
select c
}
或者,等效地,您可以添加非LINQ-to-SQL查询
let idQuery = query { for id in customerNumbers do select id }
在枚举set
产生seq<string>
然后将其用于Contains
....
where (idQuery.Contains(c.CustomerNumber))
....
或者,首先,您可以将customerNumbers
作为seq
:
let customerNumbers = set ["12345"; "23456"; "3456"] |> Set.toSeq
并将其用作直觉提示:
....
where(customerNumbers.Contains(c.CustomerNumber))
....