LinqToSql生成对数据库的错误查询

时间:2011-11-16 11:38:27

标签: linq-to-sql predicatebuilder

我遇到了LinqToSql和PredicateBuilder的问题

我有以下代码

Dim vQuery As IQueryable(Of Table1) = pContext.Table1
Dim predicate As Expression(Of System.Func(Of Table1, Boolean)) = Nothing

....

Dim predicateAdd As Expression(Of System.Func(Of Table1, Boolean)) = PredicateBuilder.True(Of Table1)()

predicateAdd = predicateAdd.And(Function(a As Table1) a.Table2.Table3.Select(Function(c) c.Column1).Contains(TextToSearch))

predicate = predicate.And(predicateAdd)

....

Me.Grid.DataSource = vQuery.Where(predicate)

生成以下对数据库的查询

SELECT [t0].[ID], ...
FROM [dbo].[Table1] AS [t0]
WHERE EXISTS(
    SELECT NULL AS [EMPTY]
    FROM [dbo].[Table2] AS [t1], [dbo].[Table3] AS [t2]
    WHERE ([t2].[Column1] = @p0) AND ([t1].[ID] = [t0].[ID]) AND ([t2].[ID] = [t1].[ID])
    )   
-- @p0 is TextToSearch

但那不是我想要的。

这行代码

a.Table2.Table3.Select(Function(c) c.Column1).Contains(TextToSearch)

必须生成对数据库的下一个查询

WHERE ([t2].[Column1] Like @p0)

但不是这个

WHERE ([t2].[Column1] = @p0)

如果我在某处错了,或者这是LinqToSql中的错误

1 个答案:

答案 0 :(得分:1)

您在调用Select()的结果上调用Contains,这与在字符串字段上调用它不同。生成的代码完全适合您所编写的内容。

由于您以这种方式调用Contains(),因此它会测试返回集合中每个项目的相等性。