LINQ系列:LINQ to SQL Select查詢

libingql發表於2014-10-24

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]

相關文章