EFCore常规操作生成的SQL语句一览

前言

EFCore的性能先不说,便捷性绝对是.Net Core平台下的ORM中最好用的,主要血统还百分百纯正。

EFCore说到底还是对数据库进行操作,无论你是写Lamda还是Linq最后总归都是要生成SQL语句。

今天这篇文章就是要列举一下我们开发中的一些常规写法在数据库中生成的SQL语句。

测试数据库:Mysql
NuGet包:Pomelo.EntityFrameworkCore.MySql
实体对象:

image

DemoContext context = new DemoContext();
DbSet<User> users = context.User;
DbSet<School> schools = context.School;

查询

ToList
users.ToList();

image

Where
users.Where(u => u.SchoolId == 1).ToList();

image

OrderBy
users.OrderBy(u => u.Age).ToList();

image

ThenBy
users.OrderBy(u => u.Age).ThenBy(u => u.SchoolId).ToList();

image

Take

返回执行数量的元素。

users.Take(2).ToList();

image

Skip

从指定数量开始忽略。

这里出现了一个奇怪的数字:18446744073709551610,这是Mysql一张表理论上能存储的最大行数。

users.Skip(2).ToList();

image

Skip And Take

我们通常的分页操作就是根据这两个方法实现的。

users.Skip(1).Take(2).ToList();

image

GroupBy
users.GroupBy(u => u.SchoolId)
.Select(u => new { count = u.Count(), item = u.FirstOrDefault() })
.ToList();

image

Join(Inner Join)
users.Join(schools, u => u.SchoolId, t => t.Id, (u, t) =>
new Student
{
    Name = u.Name,
    School = t.Name
}).ToList();

image

GroupJoin(Left Join)
users.GroupJoin(schools, u => u.SchoolId, t => t.Id, (u, t) => new { user = u, school = t })
.SelectMany(x => x.school.DefaultIfEmpty(), (u, t) =>
new Student
{
    Name = u.user.Name,
    School = t.Name
}).ToList();

image

增删改

Add
users.Add(user);

image

AddRange
users.AddRange(userList);

image

Update
users.Update(user);

image

UpdateRange
users.UpdateRange(userList);

image

Remove
users.Remove(users.FirstOrDefault(c => c.Id == 100));

image

RemoveRange
users.RemoveRange(users.Where(c => c.Age > 100));

image


搞定,这就是EFCore一些常规操作生成的Mysql语句了,SqlServer大家有时间可以自己试试,要有什么我没想但的常规操作大家也可以在评论区提一下。