1、简单查询:

SQL:

1
SELECT * FROM [Clients] WHERE Type=1 AND Deleted=0 ORDER BY ID

EF:

1
2
3
4
5
6
7
8
9
10
//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:

1
SELECT ID,Name FROM [Clients] WHERE Status=1

EF:

1
2
3
4
5
6
7
8
9
//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:

1
SELECT * FROM [Clients] WHERE ID=100

EF:

1
2
3
4
5
6
7
//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:

1
2
3
4
5
6
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:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
//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:

1
2
3
4
5
6
7
SELECT  c.ID ,
        c.ComputerName ,
        g.Name GroupName
FROM    [Clients] c
        INNER JOIN [Groups] g ON c.GroupID = g.ID
WHERE   c.Status = 1
ORDER BY g.Name

EF:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
//Func形式
    var clients = ctx.Clients.Where(c => c.Status == 1)
                .Join(ctx.Group, c => c.GroupID, g => g.ID, (c,g) => 
                {
                    c.ID,
                    c.ComputerName,
                    GroupName = g.Name
                })
                .OrderBy(item => item.GroupName)
                .ToList();
      
      
    //Linq形式1
    var clients = from c in ctx.Clients
                from g in ctx.Groups
                where c.GroupID == g.ID
                orderby g.Name
                select new
                {
                    c.ID,
                    c.ComputerName,
                    GroupName = g.Name
                };
      
    //Linq形式2
    var clients = from c in ctx.Clients
                where c.Status == 1
                join g in ctx.Group
                on c.GroupID equals g.ID into result
                from r in result
                order by r.Name
                select new
                {
                    c.ID,
                    c.ComputerName,
                    GroupName = r.Name
                };

6、分页

SQL:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
-- 方案1
SELECT TOP 10
        *
FROM    [Clients]
WHERE   Status = 1
        AND ID NOT IN ( SELECT TOP 20
                                ID
                        FROM    [Clients]
                        WHERE   Status = 1
                        ORDER BY ComputerName )
ORDER BY ComputerName
      
--方案2
SELECT  *
FROM    ( SELECT    * ,
                    ROW_NUMBER() OVER ( ORDER BY ComputerName ) AS RowNo
          FROM      [Clients]
          WHERE     Status = 1
        ) t
WHERE   RowNo >= 20
        AND RowNo < 30

EF:

1
2
3
4
5
6
7
8
9
10
11
//Func形式
    var clients = ctx.Clients.Where(c => c.Status=1)
                .OrderBy(c => c.ComputerName)
                .Skip(20)
                .Take(10)
                .ToList();
      
    //Linq形式
    var clients = (from c in ctx.Clients
                orderby c.ComputerName
                select c).Skip(20).Take(10);

7、分组统计:

SQL:

1
2
3
4
5
SELECT  Status ,
        COUNT(*) AS Cnt
FROM    [Clients]
GROUP BY Status
ORDER BY COUNT(*) DESC

EF:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
//Func形式
    var result = ctx.Clients.GroupBy(c => c.Status)
                .Select(s => new
                {
                    Status = s.Key,
                    Cnt = s.Count()
                })
                .OrderByDescending(r => r.Cnt);
      
    //Linq形式
    var result = from c in ctx.Clients
                group c by c.Status into r
                orderby r.Count() descending
                select new
                {
                    Status = r.Key,
                    Cnt = r.Count()
                };

// INNER JOIN ****************************************************************************
var TelefoneInnerJoinPessoa = Db.Telefones
.AsNoTracking()
.Join(Db.Pessoas, t => t.PessoaId, p => p.PessoaId, (t, p) => new { t, p })
.Select(s => new
{
s.t.PessoaId,
s.p.Nome,
s.t.TelefoneId,
s.t.Ddd,
s.t.Numero
}).AsQueryable();
var TGeracao = TelefoneInnerJoinPessoa.ToList();
// INNER JOIN ****************************************************************************

// LEFT JOIN ****************************************************************************
var PessoaLeftJoinTelefone = Db.Pessoas
.AsNoTracking()
.GroupJoin(Db.Telefones, p => p.PessoaId, t => t.PessoaId, (p, t) => new { p, t })
.SelectMany(temp => temp.t.DefaultIfEmpty(), (p, t) => new
{
t.PessoaId,
p.p.Nome,
TelefoneId = (int?)t.TelefoneId,
t.Ddd,
t.Numero
}).AsQueryable();
var TGeracaoLeft = PessoaLeftJoinTelefone.ToList();
// LEFT JOIN ****************************************************************************

// GROUP BY *****************************************************************************
var TelefonesCountByPessoa =
Db.Telefones.AsNoTracking()
.GroupBy(x => x.PessoaId)
.Select(x => new
{
PessoaId = x.Key,
Quantidade = (int?)x.Count()
})
.Join(Db.Pessoas, a => a.PessoaId, p => p.PessoaId, (a, p) => new { a, p })
.Select(s => new
{
s.a.PessoaId,
s.p.Nome,
Quantidade = s.a.Quantidade ?? 0
}).AsQueryable();
var TGeracaoGroup1 = TelefonesCountByPessoa.ToList();

var TelefonesCountByPessoa1 =
Db.Telefones.AsNoTracking()
.GroupBy(x => x.PessoaId)
.Select(x => new
{
PessoaId = x.Key,
Quantidade = (int?)x.Count()
}).AsQueryable();

var PessoasToTelefonesCountByPessoa1 = Db.Pessoas
.AsNoTracking()
.GroupJoin(TelefonesCountByPessoa1, p => p.PessoaId, a => a.PessoaId, (p, a) => new { p, a })
.SelectMany(temp => temp.a.DefaultIfEmpty(),
(p, a) => new
{
p.p.PessoaId,
Quantidade = a.Quantidade ?? 0,
p.p.Nome
}).AsQueryable();
var TGeracaoGroup2 = PessoasToTelefonesCountByPessoa1.ToList();

var PessoasToTelefonesCountByPessoa3 = Db.Pessoas.Select(x => new
{
x.PessoaId,
x.Nome,
Quantidade = x.Telefones.LongCount()
}).AsQueryable();
var TGeracao3 = PessoasToTelefonesCountByPessoa3.ToList();
// GROUP BY *****************************************************************************

// UNION ALL ****************************************************************************
var TbAUnionAllTbB = Db.TbAs.Select(x => new
{
x.Id,
x.Descricao
}).Concat(Db.TbBs.Select(s => new
{
s.Id,
s.Descricao
})).AsQueryable();

var GeracaoUnionAll = TbAUnionAllTbB.ToList();
// UNION ALL ****************************************************************************

//IN, NOT IN, EXISTS e NOT EXISTS
//IN
ICollection<int> Lista = Db.TbBs
.AsNoTracking()
.Select(x => x.Id).ToList<int>();
ICollection<int> lista = new List<int>() { 1, 2 }; VALORES FIXOS

var SelectIn = Db.TbAs
.AsNoTracking()
.Where(x => Lista.Contains(x.Id))
.AsQueryable();

var GeracaoTIn = SelectIn.ToList();

//NOT IN
var SelectNotIn = Db.TbAs
.AsNoTracking()
.Where(x => !Lista.Contains(x.Id))
.AsQueryable();
var GeracaoTNotIn = SelectNotIn.ToList();
//IN, NOT IN, EXISTS e NOT EXISTS

EXISTS
var SelectExists = Db.TbAs
.AsNoTracking()
.Where(x => Db.TbBs.Select(a => a.Id).Contains(x.Id))
.AsQueryable();

var GeracaoTExists = SelectExists.ToList();

EXISTS
var SelectNotExists = Db.TbAs
.AsNoTracking()
.Where(x => !Db.TbBs.Select(a => a.Id).Contains(x.Id))
.AsQueryable();

var GeracaoTNotExists = SelectNotExists.ToList();

T-SQL的IN:

Select ProductID, ProductName, CategoryID
From dbo.Products
Where CategoryID in (1, 2)

T-SQL的NOT IN:

Select ProductID, ProductName, CategoryID
From dbo.Products
Where CategoryID not in (1, 2)

Or

Select ProductID, ProductName, CategoryID
From dbo.Products
Where not CategoryID in (1, 2)

LINQ的IN:

var queryResult = from p in db.Products
where (new int?[] {1,2}).Contains(p.CategoryID)
select p;

LINQ的IN解析成SQL:

SELECT [t0].[ProductID], [t0].[ProductName], [t0].[SupplierID], [t0].[CategoryID], [t0].[QuantityPerUnit], [t0].[UnitPrice], [t0].[UnitsInStock], [t0].[UnitsOnOrder], [t0].[ReorderLevel], [t0].[Discontinued] 
FROM [dbo].[Products]AS [t0]
WHERE [t0].[CategoryID] IN (@p0, @p1)

LINQ的NOT IN:

var queryResult = from p in db.Products
where ! (new int?[] {1,2}).Contains(p.CategoryID)
select p;

LINQ的NOT IN解析成SQL:

SELECT [t0].[ProductID], [t0].[ProductName], [t0].[SupplierID], [t0].[CategoryID], [t0].[QuantityPerUnit], [t0].[UnitPrice], [t0].[UnitsInStock], [t0].[UnitsOnOrder], [t0].[ReorderLevel], [t0].[Discontinued] 
FROM [dbo].[Products]AS [t0]
WHERE NOT [t0].[CategoryID] IN (@p0, @p1)

Entity FrameWork 取表中字段的最大值

int? max = (from t in context.Test
select (int?)t.ID).Max();
int m = 0;
if (!max.HasValue)
{
m = 1;
}
else
m = (int)max + 1;

EntityFrameWork使用的更多相关文章

  1. EntityFramework Core Raw SQL

    前言 本节我们来讲讲EF Core中的原始查询,目前在项目中对于简单的查询直接通过EF就可以解决,但是涉及到多表查询时为了一步到位就采用了原始查询的方式进行.下面我们一起来看看. EntityFram ...

  2. 恋爱虽易,相处不易:当EntityFramework爱上AutoMapper

    剧情开始 为何相爱? 相处的问题? 女人的伟大? 剧情收尾? 有时候相识即是一种缘分,相爱也不需要太多的理由,一个眼神足矣,当EntityFramework遇上AutoMapper,就是如此,恋爱虽易 ...

  3. 关于这段时间学习 EntityFramework的 一点感悟

    Ado.Net,用了N多年,Entity Framework也关注了很多年. 每当项目转型的时候,就花费大巴的时间,学习一番,潮流的东西. 这个Orm很多,这个EF很火,这么多年了,我还是不敢用,虽然 ...

  4. 采用EntityFramework.Extended 对EF进行扩展(Entity Framework 延伸系列2)

    前言 Entity Framework 延伸系列目录 今天我们来讲讲EntityFramework.Extended 首先科普一下这个EntityFramework.Extended是什么,如下: 这 ...

  5. 一次修改闭源 Entity Provider 程序集以兼容新 EntityFramework 的过程

    读完本文你会知道,如何在没有源码的情况下,直接修改一个 DLL 以去除 DLL 上的强命名限制,并在该程序集上直接添加你的“友元程序集(一种特殊的 Attribute,将它应用在程序集上,使得程序集内 ...

  6. ABP文档 - EntityFramework 集成

    文档目录 本节内容: Nuget 包 DbContext 仓储 默认仓储 自定义仓储 特定的仓储基类 自定义仓储示例 仓储最佳实践 ABP可使用任何ORM框架,它已经内置了EntityFrame(以下 ...

  7. EntityFramework Core 1.1 Add、Attach、Update、Remove方法如何高效使用详解

    前言 我比较喜欢安静,大概和我喜欢研究和琢磨技术原因相关吧,刚好到了元旦节,这几天可以好好学习下EF Core,同时在项目当中用到EF Core,借此机会给予比较深入的理解,这里我们只讲解和EF 6. ...

  8. 神马玩意,EntityFramework Core 1.1又更新了?走,赶紧去围观

    前言 哦,不搞SQL了么,当然会继续,周末会继续更新,估计写完还得几十篇,但是我会坚持把SQL更新完毕,绝不会烂尾,后续很长一段时间没更新的话,不要想我,那说明我是学习新的技能去了,那就是学习英语,本 ...

  9. 问题记录:EntityFramework 一对一关系映射

    EntityFramework 一对一关系映射有很多种,比如主键作为关联,配置比较简单,示例代码: public class Teacher { public int Id { get; set; } ...

  10. EntityFramework.Extended 支持 MySql

    EntityFramework.Extended 默认不支持 MySql,需要配置如下代码: [DbConfigurationType(typeof(DbContextConfiguration))] ...

随机推荐

  1. 关于css的新思考

    因为被派去协助别的组,有机会写了一下react,发现ICE做的那一个套件用来搭建后台系统真的太给力了(插一句必入table组件其实是可以把删除添加座位基础方法加进去的).因为看了demo的代码以及对于 ...

  2. 微信公众账号 Senparc.Weixin.MP SDK 开发教程 索引

    Senparc.Weixin.MP SDK从一开始就坚持开源的状态,这个过程中得到了许多朋友的认可和支持. 目前SDK已经达到比较稳定的版本,这个过程中我觉得有必要整理一些思路和经验,和大家一起分享. ...

  3. weixin 公众平台开发

    http://www.cnblogs.com/szw/archive/2013/05/14/weixin-course-index.html http://weixin.senparc.com/

  4. 分享自己配置的HttpURLConnection请求数据工具类

    >>该工具类传入string类型url返回string类型获取结果import java.io.BufferedReader;import java.io.InputStream;impo ...

  5. PYTHON实现DES加密及base64源码

    要求是实现DES加密,解密,我是用python实现的,还是有挺多坑的,改bug就改了挺久,加密实现后,解密过程就比较轻松. 另外,附加base64编码源码 要求:输入秘钥为64位二进制数(有效位为56 ...

  6. 未在本地计算机上注册“microsoft.ACE.oledb.12.0”提供程序

    这种错误的可能性有几种,比如: 1.没有安装数据访问组件,需要安装相应版本的数据访问组件: 2.没有安装相应版本的Office客户端,需要安装相应版本的Office客户端: 3.Microsoft.J ...

  7. 手把手Maven搭建SpringMVC+Spring+MyBatis框架(超级详细版)

    手把手Maven搭建SpringMVC+Spring+MyBatis框架(超级详细版) SSM(Spring+SpringMVC+Mybatis),目前较为主流的企业级架构方案.标准的MVC设计模式, ...

  8. Caffe 源碼閱讀(四) Layer.hpp Layer.cpp

    1.Setup() Layer初始化参数 (1.完成层参数的读入.处理 2.设置底层顶层的shape,在前向传播前完成) InitMutex CheckBolbCounts: LayerSetup:d ...

  9. XML代码生成器——XMLFACTORY 简介(二)

    XML代码生成器——XMLFACTORY 简介(二)      因为春节和项目上线的原因,离写上一篇文章的时间已经好久了. 不知道是事情太多了,还是自已效率太低了.总之是时间不够用. 哎,苦逼的程序员 ...

  10. MAC下如何显示隐藏文件

    1.在终端上输入以下命令 defaults write com.apple.finder AppleShowAllFiles -bool true 2.重新启动Finder Command + Opt ...