主攻ASP.NET.3.5.MVC架构之重生: LINQ(五)
LINQ to SQL
下载LINQ to SQL Debug Visualizer
http://www.scottgu.com/blogposts/linqquery/sqlserverQueryVisualizer.zip
LINQ to SQL执行标准数据库命令
*查询文章类别ID为34的文章标题并排序取4条 Take()取元素条数 =>Top
LINQ to SQL Code
MydataDataContext data = new MydataDataContext();
var query = data.Article.Where(m => m.CategoryID == 34)
.OrderBy(m => m.Sort)
.Select(m => new { m.ArticleID, m.ArticleTitle ,m.ArticleBody})
.Take(4);
SqlCode
SELECT TOP (4) [t0].[ArticleID], [t0].[ArticleTitle], [t0].[ArticleBody]
FROM [dbo].[Article] AS [t0]
WHERE [t0].[CategoryID] = 34
ORDER BY [t0].[Sort]
*查询文章类别ID为34的文章标题并排序
LINQ to SQL Code
MydataDataContext data = new MydataDataContext();
var query = data.Article.Where(m => m.CategoryID == 34)
.OrderBy(m => m.Sort)
.Select(m => m.ArticleTitle);
SqlCode
SELECT [t0].[ArticleTitle]
FROM [dbo].[Article] AS [t0]
WHERE [t0].[CategoryID] = 34
ORDER BY [t0].[Sort]
*查询文章类别ID为34的文章标题,文章ID,文章内容并排序
LINQ to SQL Code
MydataDataContext data = new MydataDataContext();
var query = data.Article.Where(m => m.CategoryID == 34)
.OrderBy(m => m.Sort)
.Select(m => new { m.ArticleID, m.ArticleTitle ,m.ArticleBody});
SqlCode
SELECT [t0].[ArticleID], [t0].[ArticleTitle], [t0].[ArticleBody]
FROM [dbo].[Article] AS [t0]
WHERE [t0].[CategoryID] = 34
ORDER BY [t0].[Sort]
*查询文章所有项
LINQ to SQL Code
MydataDataContext data = new MydataDataContext();
var query = from m in data.Article select m;
SqlCode
SELECT [t0].[ArticleID], [t0].[CategoryID], [t0].[ArticleTitle], [t0].[ArticleBody], [t0].[IsTop], [t0].[Sort], [t0].[CreateTime], [t0].[SysUserID], [t0].[State]
FROM [dbo].[Article] AS [t0]
*查询文章选择项
LINQ to SQL Code
MydataDataContext data = new MydataDataContext();
var query = data.Article.Select(m => new { m.ArticleID, m.ArticleTitle });
SqlCode
SELECT [t0].[ArticleID], [t0].[ArticleTitle]
FROM [dbo].[Article] AS [t0]
IEnumerable和IEnumerable<T>接口
IQueryProvider和IQueryable<T>接口
IQueryable
Lambda表达式
Code:
MyDataDataContext data = new MyDataDataContext(); //使用LINQ类
var s = from n in data.Article where n.ArticleID == 21 select n; //执行查询
foreach (var t in s) //遍历对象
{
Response.Write(t.ArticleTitle.ToString() + "<br/>"); //输出对象
}