本文使用LINQPad 6说明select语句性能问题。
Customers.Where(x => x.City.Contains("London"))
.ToDictionary(c => c.CustomerID, c => c.ContactName);
Customers.Where(x => x.City.Contains("London"))
.Select(x => new { x.CustomerID, x.ContactName })
.ToDictionary(c => c.CustomerID, c => c.ContactName);
对应的sql语句为
exec sp_executesql N'SELECT [t0].[CustomerID], [t0].[CompanyName], [t0].[ContactName], [t0].[ContactTitle], [t0].[Address],
[t0].[City], [t0].[Region], [t0].[PostalCode], [t0].[Country], [t0].[Phone], [t0].[Fax], [t0].[ParentCompanyID]
FROM [Customers] AS [t0]
WHERE [t0].[City] LIKE @p0',N'@p0 nvarchar(4000)',@p0=N'%London%'
exec sp_executesql N'SELECT [t0].[CustomerID], [t0].[ContactName]
FROM [Customers] AS [t0]
WHERE [t0].[City] LIKE @p0',N'@p0 nvarchar(4000)',@p0=N'%London%'
区别:使用select语句能够减少返回的column,提高性能,尤其在某些column数据本身很大的情况,例如保存image的column
实际应用程序中,大多不会使用匿名类型,而是返回具体的类型,可以创建新的类,配合automapping。 或者使用原始查询,或者自己在ado.net上进行封装开发类似的库。