LINQ系列:LINQ to SQL Select查询
Posted dekevin技术博客
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了LINQ系列:LINQ to SQL Select查询相关的知识,希望对你有一定的参考价值。
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]
以上是关于LINQ系列:LINQ to SQL Select查询的主要内容,如果未能解决你的问题,请参考以下文章
如何检测 Linq to SQL 中的 Select n+1 问题?