0

我想通过方法参数将“Where”子句传递给方法,但我发现 where 子句没有发送到数据库服务器。查询实际获取所有记录,然后 EF 在客户端应用程序中应用“Where”。

这是一个演示我的问题的示例:

// ID  Name         Colour
// -----------------------
// 3   RED_CAR      RED
// 4   WHITE_CAR    WHITE
// 5   BLUE_CAR     BLUE

using (QDBEntities db = new QDBEntities())
{
    // #1 - no variable "Where" - where sent to server, result is correct.
    foreach (var car in db.Cars.Where(r => r.Colour == "RED"))
        Console.WriteLine(car.ID + " " + car.Name);
    // Output:      3 RED_CAR
    // Profiler:   ... FROM [dbo].[Car] AS [Extent1]
    // WHERE N'RED' = [Extent1].[Colour]

    // #2 - using a variable "Where" - where NOT sent to server, result is correct.
    Func<Car, bool> where = new Func<Car, bool>(r => r.Colour == "RED");
    foreach (var car in db.Cars.Where(where))
        Console.WriteLine(car.ID + " " + car.Name);
    // Output:      3 RED_CAR
    // Profiler:    FROM [dbo].[Car] AS [Extent1] ** NO WHERE CLAUSE **
}
4

1 回答 1

3

您需要传递一个表达式树Where()以便 EF 可以看到它做了什么并将其转换为 SQL。

更改Func<Car, bool>Expression<Func<Car, bool>>

于 2013-07-23T17:55:34.630 回答