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大家有时间可以自己试试,要有什么我没想但的常规操作大家也可以在评论区提一下。

posted @   畅饮无绪  阅读(990)  评论(4编辑  收藏  举报
点击右上角即可分享
微信分享提示