标签:
Entity Framework是个好东西,虽然没有Hibernate功能强大,但使用更简便。今天整理一下常见SQL如何用EF来表达,Func形式和Linq形式都会列出来(本人更喜欢Func形式)。
1、简单查询:
SQL:
SELECT * FROM [Clients] WHERE Type=1 AND Deleted=0 ORDER BY ID
EF:
//Func形式 var clients = ctx.Clients.Where(c => c.Type == 1 && c.Deleted == 0) .OrderBy(c => c.ID) .ToList(); //Linq形式 var clients = from c in ctx.Clients where c.Type == 1 && c.Deleted==0 orderby c.ID select c;
2、查询部分字段:
SQL:
SELECT ID,Name FROM [Clients] WHERE Status=1
EF:
//Func形式 var clients = ctx.Clients.Where(c => c.Status == 1) .Select(c => new { c.ID, Name = c.ComputerName }) .ToList(); //Linq形式 var clients = from c in ctx.Clients where c.Status == 1 select new { c.ID, Name = c.ComputerName }; :
3、查询单一记录:
SQL:
SELECT * FROM [Clients] WHERE ID=100
EF:
//Func形式 var client = ctx.Clients.FirstOrDefault(c => c.ID == 100); //Linq形式 var client = (from c in ctx.Clients where c.ID = 100 select c).FirstOrDefault();
4、LEFT JOIN 连接查询
SQL:
SELECT c.ID,c.ComputerName,g.Name GroupName FROM [Clients] c LEFT JOIN [Groups] g ON c.GroupID = g.ID WHERE c.Status=1
EF:
//Func形式 var clients = ctx.Clients.Where(c => c.Status == 1) .Select(c => new { c.ID, c.ComputerName, GroupName = ctx.Groups.FirstOrDefault(g => g.ID == c.GroupID).Name }) .ToList(); //Linq形式 var clients = from c in ctx.Clients where c.Status == 1 select new { c.ID, c.ComputerName, GroupName = (from g in ctx.Groups where g.ID == c.GroupID select g.Name).FirstOrDefault() };
5、INNER JOIN 连接查询:
SQL:
EF:
6、分页
SQL:
EF:
7、分组统计:
SQL:
EF:
未完待续……
标签:
原文地址:http://www.cnblogs.com/longyi/p/5447832.html