LINQ系列:LINQ to SQL Select查询
1. 查询全部字段
using (NorthwindContext context = new NorthwindContext()) { var expr = context.Products; foreach (var item in expr) { Console.WriteLine(item.ProductName); } }
SELECT [Extent1].[ProductID] AS [ProductID], [Extent1].[CategoryID] AS [CategoryID], [Extent1].[ProductName] AS [ProductName], [Extent1].[UnitPrice] AS [UnitPrice], [Extent1].[Discontinued] AS [Discontinued] FROM [dbo].[Product] AS [Extent1]
2. 查询指定字段
var expr = context.Products .Select(p => new { p.ProductID, p.ProductName });
var expr = from p in context.Products select new { 商品ID = p.ProductID, 商品名称 = p.ProductName };
上述两种形式所生成的SQL是一样的。
SELECT [Extent1].[ProductID] AS [ProductID], [Extent1].[ProductName] AS [ProductName] FROM [dbo].[Product] AS [Extent1]
3. First/FirstOrDefault
var expr = context.Products.First();
SELECT TOP (1) [c].[ProductID] AS [ProductID], [c].[CategoryID] AS [CategoryID], [c].[ProductName] AS [ProductName], [c].[UnitPrice] AS [UnitPrice], [c].[Discontinued] AS [Discontinued] FROM [dbo].[Product] AS [c]
4. Single/SingleOrDefault
var expr = context.Products .SingleOrDefault(p => p.ProductID == 1);
SELECT TOP (2) [Extent1].[ProductID] AS [ProductID], [Extent1].[CategoryID] AS [CategoryID], [Extent1].[ProductName] AS [ProductName], [Extent1].[UnitPrice] AS [UnitPrice], [Extent1].[Discontinued] AS [Discontinued] FROM [dbo].[Product] AS [Extent1] WHERE 1 = [Extent1].[ProductID]