我想通过方法参数将“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 **
}