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 });
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]

 

郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。