
FreeSql简介:
功能简单、强大的对象关系映射(O/RM)组件,支持 .NET Core 2.1+、.NET Framework 4.0+、Xamarin,国产首个支持 AOT 发布的 ORM✨
FreeSql官网:入门 | FreeSql
第一步:创建数据库
这里使用的是Sqlite数据库:
Sqlite数据库帮助文档:
如何安装SQLite数据库_sqlite数据库下载-CSDN博客
Navicat工具使用SQLite数据库
数据库设计代码:
sql
/*
Navicat Premium Data Transfer
Source Server : 2
Source Server Type : SQLite
Source Server Version : 3035005
Source Schema : main
Target Server Type : SQLite
Target Server Version : 3035005
File Encoding : 65001
Date: 30/11/2026 19:57:40
*/
PRAGMA foreign_keys = false;
-- ----------------------------
-- Table structure for t_user
-- ----------------------------
DROP TABLE IF EXISTS "t_user";
CREATE TABLE "t_user" (
"Id" INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT,
"Name" NVARCHAR(50) NOT NULL,
"Age" INTEGER NOT NULL
);
-- ----------------------------
-- Records of t_user
-- ----------------------------
INSERT INTO "t_user" VALUES (2, 'Hsuan Chi Yuen', 59);
INSERT INTO "t_user" VALUES (4, 'Walter Thompson', 699);
INSERT INTO "t_user" VALUES (5, 'Otsuka Shino', 39);
INSERT INTO "t_user" VALUES (6, 'Tao Fat', 572);
INSERT INTO "t_user" VALUES (7, 'Fong Siu Wai', 378);
INSERT INTO "t_user" VALUES (8, 'Cheung Hok Yau', 219);
INSERT INTO "t_user" VALUES (9, 'Xu Zhennan', 323);
INSERT INTO "t_user" VALUES (10, 'Linda Holmes', 568);
INSERT INTO "t_user" VALUES (11, 'Murakami Aoshi', 585);
INSERT INTO "t_user" VALUES (12, 'Dong Xiaoming', 968);
INSERT INTO "t_user" VALUES (13, 'Chow Sze Kwan', 607);
INSERT INTO "t_user" VALUES (14, 'Nishimura Daisuke', 931);
INSERT INTO "t_user" VALUES (15, 'Cai Zhennan', 384);
INSERT INTO "t_user" VALUES (16, 'Xiao Xiuying', 658);
INSERT INTO "t_user" VALUES (17, 'Helen Dunn', 713);
INSERT INTO "t_user" VALUES (18, 'Ota Ryota', 400);
INSERT INTO "t_user" VALUES (19, 'Tian Xiaoming', 645);
INSERT INTO "t_user" VALUES (20, 'Kojima Shino', 538);
INSERT INTO "t_user" VALUES (21, 'Xie Jialun', 234);
INSERT INTO "t_user" VALUES (22, 'He Xiaoming', 163);
INSERT INTO "t_user" VALUES (23, 'Mori Mitsuki', 595);
INSERT INTO "t_user" VALUES (24, 'Travis Butler', 319);
INSERT INTO "t_user" VALUES (25, 'Mark Wright', 189);
INSERT INTO "t_user" VALUES (26, 'Long Rui', 550);
INSERT INTO "t_user" VALUES (27, 'Keith Reynolds', 599);
INSERT INTO "t_user" VALUES (28, 'Ota Hazuki', 84);
INSERT INTO "t_user" VALUES (29, 'Wang Lu', 126);
INSERT INTO "t_user" VALUES (30, 'Sun Jiehong', 716);
INSERT INTO "t_user" VALUES (1001, '张三', 60);
-- ----------------------------
-- Auto increment value for t_user
-- ----------------------------
UPDATE "sqlite_sequence" SET seq = 1001 WHERE name = 't_user';
PRAGMA foreign_keys = true;
User.cs实体类
cs
public class User
{
public int Id { get; set; }
public string Name { get; set; }
public int Age { get; set; }
//public string CreateTime { get; set; }
}
第二步:创建C#.Net Framework项目

安装FreeSql安装包
sql
Install-Package FreeSql
Install-Package FreeSql.Provider.Sqlite
//也可以安装,包含所有的Free包
Install-Package FreeSql.All
第三步:创建FreeSql相关类和方法
创建FreeSqlHelper.cs
cs
using FreeSql;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Linq.Expressions;
namespace _2
{
/// <summary>
/// 分页结果容器
/// </summary>
public class PageResult<T>
{
public int Page { get; set; }
public int PageSize { get; set; }
public long Total { get; set; }
public List<T> Items { get; set; }
public int TotalPages => PageSize <= 0 ? 0 : (int)((Total + PageSize - 1) / PageSize);
public bool HasPrev => Page > 1;
public bool HasNext => Page < TotalPages;
public PageResult()
{
Items = new List<T>();
}
}
public static class FreeSqlHelper
{
// ==================== 初始化 ====================
static Lazy<IFreeSql> sqliteLazy = new Lazy<IFreeSql>(() =>
{
// SQLite 不会自动建目录,先确保 Data 目录存在
var dbDir = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Data");
Directory.CreateDirectory(dbDir);
var dbPath = Path.Combine(dbDir, "2.db");
var fsql = new FreeSqlBuilder()
.UseMonitorCommand(cmd => Debug.WriteLine($"Sql:{cmd.CommandText}"))
.UseConnectionString(DataType.Sqlite, $"Data Source={dbPath}")
.UseAutoSyncStructure(true)
.Build();
// ★ Fluent 配置,必须在 Build 之后、SyncStructure 之前
fsql.CodeFirst.ConfigEntity<User>(eb =>
{
eb.Name("t_user");
eb.Property(a => a.Id).IsPrimary(true).IsIdentity(true);
eb.Property(a => a.Name).IsNullable(false).StringLength(50);
eb.Property(a => a.Age).IsNullable(false);
});
fsql.CodeFirst.SyncStructure<User>(); // 建表要在配置之后
return fsql;
});
public static IFreeSql Sqlite => sqliteLazy.Value;
// ==================== 链式入口(复杂查询自己拼) ====================
public static ISelect<T> Select<T>() where T : class => Sqlite.Select<T>();
public static IInsert<T> Insert<T>() where T : class => Sqlite.Insert<T>();
public static IUpdate<T> Update<T>() where T : class => Sqlite.Update<T>();
public static IDelete<T> Delete<T>() where T : class => Sqlite.Delete<T>();
#region 增
/// <summary>插入单条,返回受影响行数</summary>
public static int Add<T>(T entity) where T : class
{
if (entity == null) return 0;
return (int)Sqlite.Insert<T>(entity).ExecuteAffrows();
}
/// <summary>插入单条,返回自增主键</summary>
public static long AddReturnIdentity<T>(T entity) where T : class
{
if (entity == null) return 0;
return Sqlite.Insert<T>(entity).ExecuteIdentity();
}
/// <summary>批量插入,返回受影响行数</summary>
public static int AddRange<T>(IEnumerable<T> list) where T : class
{
if (list == null) return 0;
var arr = list as IList<T> ?? list.ToList();
if (arr.Count == 0) return 0;
return (int)Sqlite.Insert<T>(arr).ExecuteAffrows();
}
#endregion
#region 删
/// <summary>按实体删除(主键定位)</summary>
public static int DeleteEntity<T>(T entity) where T : class
{
if (entity == null) return 0;
return (int)Sqlite.Delete<T>(entity).ExecuteAffrows();
}
/// <summary>按条件删除</summary>
public static int DeleteByWhere<T>(Expression<Func<T, bool>> where) where T : class
{
if (where == null) return 0;
return (int)Sqlite.Delete<T>().Where(where).ExecuteAffrows();
}
#endregion
#region 改
/// <summary>按实体全字段更新(主键定位,未赋值的属性会被写成默认值)</summary>
public static int UpdateEntity<T>(T entity) where T : class
{
if (entity == null) return 0;
return (int)Sqlite.Update<T>().SetSource(entity).ExecuteAffrows();
}
#endregion
#region 查
/// <summary>按主键查询单条</summary>
public static T GetById<T>(object id) where T : class
{
return Sqlite.Select<T>().WhereDynamic(id).First();
}
/// <summary>条件查询单条,没有则返回 null</summary>
public static T GetOne<T>(Expression<Func<T, bool>> where) where T : class
{
return Sqlite.Select<T>().Where(where).First();
}
/// <summary>条件查询列表</summary>
public static List<T> GetList<T>(Expression<Func<T, bool>> where = null) where T : class
{
var query = Sqlite.Select<T>();
if (where != null) query = query.Where(where);
return query.ToList();
}
/// <summary>是否存在</summary>
public static bool Exists<T>(Expression<Func<T, bool>> where) where T : class
{
return Sqlite.Select<T>().Any(where);
}
/// <summary>计数,不传条件则统计全表</summary>
public static long Count<T>(Expression<Func<T, bool>> where = null) where T : class
{
var query = Sqlite.Select<T>();
if (where != null) query = query.Where(where);
return query.Count();
}
/// <summary>
/// 分页查询
/// </summary>
/// <param name="page">页码,从 1 开始</param>
/// <param name="pageSize">每页条数</param>
/// <param name="where">筛选条件,可空</param>
/// <param name="order">排序,例如 s => s.OrderBy(a => a.Id)</param>
public static PageResult<T> GetPage<T>(int page, int pageSize,
Expression<Func<T, bool>> where = null,
Func<ISelect<T>, ISelect<T>> order = null) where T : class
{
if (page < 1) page = 1;
if (pageSize < 1) pageSize = 10;
var countQuery = Sqlite.Select<T>();
if (where != null) countQuery = countQuery.Where(where);
long total = countQuery.Count();
var query = Sqlite.Select<T>();
if (where != null) query = query.Where(where);
if (order != null) query = order(query);
var items = query.Page(page, pageSize).ToList();
return new PageResult<T>
{
Page = page,
PageSize = pageSize,
Total = total,
Items = items
};
}
#endregion
#region 原生 SQL / 联合查询
/// <summary>
/// 执行查询 SQL,结果映射到 T
/// 联合查询示例:select a.Id, a.Name, b.DeptName from t_user a left join t_dept b on a.DeptId = b.Id
/// </summary>
public static List<T> QueryBySql<T>(string sql, object parms = null)
{
return parms == null
? Sqlite.Ado.Query<T>(sql)
: Sqlite.Ado.Query<T>(sql, parms);
}
/// <summary>执行增删改 SQL,返回受影响行数</summary>
public static int ExecuteSql(string sql, object parms = null)
{
return Sqlite.Ado.ExecuteNonQuery(sql, parms);
}
/// <summary>查询单个标量值</summary>
public static T ScalarBySql<T>(string sql, object parms = null)
{
var list = QueryBySql<T>(sql, parms);
return list.Count > 0 ? list[0] : default(T);
}
#endregion
#region 事务
/// <summary>
/// 同线程事务,异常自动回滚(FreeSql 内置)
/// 用法:FreeSqlHelper.Transaction(() => { FreeSqlHelper.Add(u1); FreeSqlHelper.Add(u2); });
/// 限制:事务体内不能切换线程、不能用 async
/// </summary>
public static void Transaction(Action work)
{
if (work == null) return;
Sqlite.Transaction(work);
}
/// <summary>带返回值的事务</summary>
public static T Transaction<T>(Func<T> work)
{
if (work == null) throw new ArgumentNullException("work");
T result = default(T);
Sqlite.Transaction(() => { result = work(); });
return result;
}
#endregion
}
}
创建User.cs实体类
cs
using System;
namespace _2
{
public class User
{
public int Id { get; set; }
public string Name { get; set; }
public int Age { get; set; }
//public string CreateTime { get; set; }
}
}
3.1 初始化链:每一步都在为下一步铺路
static Lazy<IFreeSql> sqliteLazy = new Lazy<IFreeSql>(() =>
{
Directory.CreateDirectory(dbDir); // ① 建目录(SQLite 不会自动建)
var fsql = new FreeSqlBuilder()
.UseMonitorCommand(...) // ② 调试输出 SQL
.UseConnectionString(...) // ③ 指定 Provider + 连接串
.UseAutoSyncStructure(true) // ④ 自动同步表结构
.Build(); // ⑤ 构建出运行时实例
fsql.CodeFirst.ConfigEntity<User>(...); // ⑥ Fluent 配置(必须在 Build 之后)
fsql.CodeFirst.SyncStructure<User>(); // ⑦ 建表(必须在配置之后)
return fsql;
});
| 步骤 | 为什么必须在这个位置 | 顺序错了会怎样 |
|---|---|---|
① CreateDirectory |
SQLite 不会创建父目录 | 报 unable to open database file,且不会提示是目录问题 |
② UseMonitorCommand |
想在 VS 输出窗口看到真实 SQL | 排错时只能猜 FreeSql 把 lambda 翻成了什么 |
③ UseConnectionString |
让 Provider 决定方言(分页语法、自增回填方式) | 用错 Provider → 生成非目标库的 SQL |
④ UseAutoSyncStructure |
开发期免手写 DDL | 关掉后表不存在就直接报"no such table" |
⑤ Build() |
返回可配置的运行时实例 | Builder 上的 ConfigEntity 无效 |
⑥ ConfigEntity |
必须在 Build 之后 | 配置不生效,表按默认约定叫 User |
⑦ SyncStructure |
必须在配置之后 | 先建出一张 User 表,之后代码却认 t_user |
为什么用 Lazy<IFreeSql> 而不是 static readonly:
-
延迟初始化------启动时不连库,界面秒开,第一次真正用到才建库;
-
线程安全 ------默认
ExecutionAndPublication模式,多线程并发访问也只执行一次工厂委托,绝不会出现两个IFreeSql; -
异常语义------工厂抛异常后 Lazy 会永久处于"失败"状态,后续访问重复抛同一异常。好处是错误不被吞;坏处是运行中修好环境也无法自愈(需重启)。
IFreeSql本身是线程安全的,可被多线程共享(内部按需从连接池取连接)。但它的Transaction(...)基于 AsyncLocal,只在当前执行上下文有效------这点后面单独说。
3.2 UseAutoSyncStructure(true) 的真实代价
它确实省事:表不存在就建、缺列就加、类型不符就尝试改(绝不会删列删表)。但三个副作用要清楚:
| 副作用 | 场景 | 应对 |
|---|---|---|
| 并发 DDL 锁冲突 | 多个程序实例同时启动 | 生产改 false,用迁移脚本管 DDL |
| 结构变更"静默发生" | 绕过 DBA 审核 | 生产改 false |
| 大表 ALTER 长时间锁表 | 百万级表加列 | 用专业迁移工具(分表重建) |
推荐策略 :开发期 true,发布时改 false,DDL 走脚本。
3.3 方法速查表
| 分类 | 方法 | 返回 | 底层动作 | 关键注意点 |
|---|---|---|---|---|
| 增 | Add(entity) |
受影响行数 | INSERT |
只告诉"成了",不给 Id |
| 增 | AddReturnIdentity(entity) |
自增主键 | INSERT + last_insert_rowid() |
原子操作,并发不串号;非自增主键返回 0 |
| 增 | AddRange(list) |
受影响行数 | 多值 INSERT |
先 as IList 零拷贝,空集合不发 SQL |
| 删 | DeleteEntity(entity) |
受影响行数 | DELETE WHERE Id=@id |
只用主键,其他字段不参与条件 |
| 删 | DeleteByWhere(where) |
受影响行数 | DELETE WHERE ... |
where=null 时什么都不做(有意保险) |
| 改 | UpdateEntity(entity) |
受影响行数 | 全字段 UPDATE |
未赋值的属性会被默认值覆盖 |
| 查 | GetById(id) |
实体或 null | WhereDynamic(id) |
不必知道主键叫什么,通用 |
| 查 | GetOne(where) |
实体或 null | SELECT ... LIMIT 1 |
无结果返回 null,不抛异常 |
| 查 | GetList(where) |
List<T> |
SELECT ... |
where=null 查全表 |
| 查 | Exists(where) |
bool | EXISTS/COUNT |
只查"有没有",不取整行 |
| 查 | Count(where) |
long | COUNT(*) |
Sqlite 的 COUNT 本就是 64 位 |
| 查 | GetPage(page,size,where,order) |
PageResult<T> |
2 条 SQL | 服务端分页,排序进 ORDER BY |
| 原生 | QueryBySql<T>(sql,parms) |
List<T> |
Ado.Query |
列名→属性名映射,缺列静默取默认值 |
| 原生 | ExecuteSql(sql,parms) |
受影响行数 | Ado.ExecuteNonQuery |
必须参数化,不能拼串 |
| 原生 | ScalarBySql<T>(sql,parms) |
单值 | 查询后取首行首列 | 多行结果会被丢弃 |
| 事务 | Transaction(Action) |
void | 环境事务 + 自动回滚 | 不能跨线程、不能跨 await |
| 事务 | Transaction<T>(Func<T>) |
T | 同上,闭包带出返回值 | 抛异常时返回 default(T) |
3.4 UpdateEntity 是这份代码里最危险的方法
"全字段更新"意味着实体的每个属性都会进 SET 子句,没赋值的属性用它自己的默认值覆盖数据库:
// 危险:以为只改 Name,实际把 Age 写成了 0
FreeSqlHelper.UpdateEntity(new User { Id = 1, Name = "张三" });
// 正确:显式点名要改的列(Form1.btnUpdate_Click 就是这么写的)
FreeSqlHelper.Update<User>()
.Set(a => a.Name, name)
.Set(a => a.Age, age)
.Where(a => a.Id == 1)
.ExecuteAffrows();
判断标准很简单:"整行覆盖"用 UpdateEntity,"改个别字段"用 Set。后者改动范围可见,加字段时最安全。
3.5 GetPage 为什么发两条 SQL
var countQuery = Sqlite.Select<T>(); // ① 不带 order、不带 Page
if (where != null) countQuery = countQuery.Where(where);
long total = countQuery.Count(); // → SELECT COUNT(*) ...
var query = Sqlite.Select<T>(); // ② 带 order、带 Page
if (where != null) query = query.Where(where);
if (order != null) query = order(query);
var items = query.Page(page, pageSize).ToList(); // → SELECT * ... LIMIT ? OFFSET ?
关键设计:countQuery 故意不带排序。 ORDER BY 对 COUNT 毫无意义,带上只会让数据库多做一次全表排序------大表上是实打实的损耗。
| 取舍 | 说明 |
|---|---|
| 为什么必须 COUNT | 要显示"共 52 条 / 第 3/6 页",必须知道总数 |
| COUNT 的成本 | SQLite 的 COUNT(*) 走全表扫描,大表有开销 |
| 想省 COUNT | 只取 pageSize + 1 条,用"有没有多出一条"判断是否有下一页(信息变少) |
| 本示例选择 | 信息完整优先(桌面单机 Sqlite,成本可接受) |
3.6 一个容易踩的语法坑
// 错:返回值被丢弃,条件等于没加
Sqlite.Select<User>().Where(a => a.Name == "x");
query.Where(where);
// 对:ISelect 是不可变链式对象,必须把返回值赋回去
query = query.Where(where);
3.7 事务的三条硬限制
FreeSqlHelper.Transaction(() => {
FreeSqlHelper.Add(u1);
FreeSqlHelper.Add(u2); // 两条在同一个事务里,异常则全部回滚
});
原理:FreeSql 把事务对象挂在 AsyncLocal (执行上下文级),所以事务体内任何通过同一 IFreeSql 发出的命令都会自动并入------不用手动传事务对象,这是它比手写 ADO.NET 省事的地方。
但因此有三条限制:
| 限制 | 原因 | 后果 |
|---|---|---|
不能切线程(Task.Run/Thread/Parallel) |
新线程脱离执行上下文 | 新线程用独立连接,回滚管不到它 |
不能跨 await |
续体可能落到别的线程 | 部分操作脱离事务 |
| 事务必须短 | SQLite 是文件级写锁 | 长事务把其他写入全卡死(SQLITE_BUSY) |
需要异步事务要用 TransactionAsync;需要长事务说明设计有问题,应该拆批。
第四部:书写页面和后端相关代码
前度页面设计


前端代码:
cs
namespace _2
{
partial class Form1
{
/// <summary>
/// 必需的设计器变量。
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// 清理所有正在使用的资源。
/// </summary>
/// <param name="disposing">如果应释放托管资源,为 true;否则为 false。</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows 窗体设计器生成的代码
/// <summary>
/// 设计器支持所需的方法 - 不要修改
/// 使用代码编辑器修改此方法的内容。
/// </summary>
private void InitializeComponent()
{
this.dataGridView1 = new System.Windows.Forms.DataGridView();
this.lblId = new System.Windows.Forms.Label();
this.txtId = new System.Windows.Forms.TextBox();
this.lblName = new System.Windows.Forms.Label();
this.txtName = new System.Windows.Forms.TextBox();
this.lblAge = new System.Windows.Forms.Label();
this.txtAge = new System.Windows.Forms.TextBox();
this.btnAdd = new System.Windows.Forms.Button();
this.btnUpdate = new System.Windows.Forms.Button();
this.btnDelete = new System.Windows.Forms.Button();
this.btnQuery = new System.Windows.Forms.Button();
this.btnClear = new System.Windows.Forms.Button();
this.lblPageSize = new System.Windows.Forms.Label();
this.cboPageSize = new System.Windows.Forms.ComboBox();
this.lblPageSizeUnit = new System.Windows.Forms.Label();
this.btnFirst = new System.Windows.Forms.Button();
this.btnPrev = new System.Windows.Forms.Button();
this.lblPage = new System.Windows.Forms.Label();
this.btnNext = new System.Windows.Forms.Button();
this.btnLast = new System.Windows.Forms.Button();
this.lblJump = new System.Windows.Forms.Label();
this.txtJump = new System.Windows.Forms.TextBox();
this.lblJumpUnit = new System.Windows.Forms.Label();
this.btnJump = new System.Windows.Forms.Button();
((System.ComponentModel.ISupportInitialize)(this.dataGridView1)).BeginInit();
this.SuspendLayout();
//
// dataGridView1
//
this.dataGridView1.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize;
this.dataGridView1.Location = new System.Drawing.Point(20, 108);
this.dataGridView1.Name = "dataGridView1";
this.dataGridView1.RowHeadersWidth = 62;
this.dataGridView1.RowTemplate.Height = 30;
this.dataGridView1.Size = new System.Drawing.Size(1266, 420);
this.dataGridView1.TabIndex = 0;
//
// lblId
//
this.lblId.AutoSize = true;
this.lblId.Location = new System.Drawing.Point(20, 26);
this.lblId.Name = "lblId";
this.lblId.Size = new System.Drawing.Size(35, 18);
this.lblId.TabIndex = 1;
this.lblId.Text = "ID:";
//
// txtId
//
this.txtId.Location = new System.Drawing.Point(55, 20);
this.txtId.Name = "txtId";
this.txtId.ReadOnly = true;
this.txtId.Size = new System.Drawing.Size(70, 28);
this.txtId.TabIndex = 2;
//
// lblName
//
this.lblName.AutoSize = true;
this.lblName.Location = new System.Drawing.Point(135, 26);
this.lblName.Name = "lblName";
this.lblName.Size = new System.Drawing.Size(53, 18);
this.lblName.TabIndex = 3;
this.lblName.Text = "姓名:";
//
// txtName
//
this.txtName.Location = new System.Drawing.Point(185, 20);
this.txtName.Name = "txtName";
this.txtName.Size = new System.Drawing.Size(160, 28);
this.txtName.TabIndex = 4;
//
// lblAge
//
this.lblAge.AutoSize = true;
this.lblAge.Location = new System.Drawing.Point(355, 26);
this.lblAge.Name = "lblAge";
this.lblAge.Size = new System.Drawing.Size(53, 18);
this.lblAge.TabIndex = 5;
this.lblAge.Text = "年龄:";
//
// txtAge
//
this.txtAge.Location = new System.Drawing.Point(405, 20);
this.txtAge.Name = "txtAge";
this.txtAge.Size = new System.Drawing.Size(70, 28);
this.txtAge.TabIndex = 6;
//
// btnAdd
//
this.btnAdd.Location = new System.Drawing.Point(20, 60);
this.btnAdd.Name = "btnAdd";
this.btnAdd.Size = new System.Drawing.Size(100, 34);
this.btnAdd.TabIndex = 7;
this.btnAdd.Text = "新增";
this.btnAdd.UseVisualStyleBackColor = true;
//
// btnUpdate
//
this.btnUpdate.Location = new System.Drawing.Point(130, 60);
this.btnUpdate.Name = "btnUpdate";
this.btnUpdate.Size = new System.Drawing.Size(100, 34);
this.btnUpdate.TabIndex = 8;
this.btnUpdate.Text = "修改";
this.btnUpdate.UseVisualStyleBackColor = true;
//
// btnDelete
//
this.btnDelete.Location = new System.Drawing.Point(240, 60);
this.btnDelete.Name = "btnDelete";
this.btnDelete.Size = new System.Drawing.Size(100, 34);
this.btnDelete.TabIndex = 9;
this.btnDelete.Text = "删除";
this.btnDelete.UseVisualStyleBackColor = true;
//
// btnQuery
//
this.btnQuery.Location = new System.Drawing.Point(350, 60);
this.btnQuery.Name = "btnQuery";
this.btnQuery.Size = new System.Drawing.Size(100, 34);
this.btnQuery.TabIndex = 10;
this.btnQuery.Text = "查询";
this.btnQuery.UseVisualStyleBackColor = true;
//
// btnClear
//
this.btnClear.Location = new System.Drawing.Point(460, 60);
this.btnClear.Name = "btnClear";
this.btnClear.Size = new System.Drawing.Size(100, 34);
this.btnClear.TabIndex = 11;
this.btnClear.Text = "清空输入";
this.btnClear.UseVisualStyleBackColor = true;
//
// lblPageSize
//
this.lblPageSize.AutoSize = true;
this.lblPageSize.Location = new System.Drawing.Point(1103, 551);
this.lblPageSize.Name = "lblPageSize";
this.lblPageSize.Size = new System.Drawing.Size(44, 18);
this.lblPageSize.TabIndex = 12;
this.lblPageSize.Text = "每页";
//
// cboPageSize
//
this.cboPageSize.Location = new System.Drawing.Point(1143, 545);
this.cboPageSize.Name = "cboPageSize";
this.cboPageSize.Size = new System.Drawing.Size(80, 26);
this.cboPageSize.TabIndex = 13;
//
// lblPageSizeUnit
//
this.lblPageSizeUnit.AutoSize = true;
this.lblPageSizeUnit.Location = new System.Drawing.Point(1229, 551);
this.lblPageSizeUnit.Name = "lblPageSizeUnit";
this.lblPageSizeUnit.Size = new System.Drawing.Size(26, 18);
this.lblPageSizeUnit.TabIndex = 14;
this.lblPageSizeUnit.Text = "条";
//
// btnFirst
//
this.btnFirst.Location = new System.Drawing.Point(20, 545);
this.btnFirst.Name = "btnFirst";
this.btnFirst.Size = new System.Drawing.Size(90, 34);
this.btnFirst.TabIndex = 15;
this.btnFirst.Text = "首页";
this.btnFirst.UseVisualStyleBackColor = true;
//
// btnPrev
//
this.btnPrev.Location = new System.Drawing.Point(118, 545);
this.btnPrev.Name = "btnPrev";
this.btnPrev.Size = new System.Drawing.Size(100, 34);
this.btnPrev.TabIndex = 16;
this.btnPrev.Text = "< 上一页";
this.btnPrev.UseVisualStyleBackColor = true;
//
// lblPage
//
this.lblPage.Location = new System.Drawing.Point(226, 553);
this.lblPage.Name = "lblPage";
this.lblPage.Size = new System.Drawing.Size(400, 20);
this.lblPage.TabIndex = 17;
this.lblPage.Text = "第 1/1 页";
//
// btnNext
//
this.btnNext.Location = new System.Drawing.Point(634, 545);
this.btnNext.Name = "btnNext";
this.btnNext.Size = new System.Drawing.Size(100, 34);
this.btnNext.TabIndex = 18;
this.btnNext.Text = "下一页 >";
this.btnNext.UseVisualStyleBackColor = true;
//
// btnLast
//
this.btnLast.Location = new System.Drawing.Point(742, 545);
this.btnLast.Name = "btnLast";
this.btnLast.Size = new System.Drawing.Size(90, 34);
this.btnLast.TabIndex = 19;
this.btnLast.Text = "末页";
this.btnLast.UseVisualStyleBackColor = true;
//
// lblJump
//
this.lblJump.AutoSize = true;
this.lblJump.Location = new System.Drawing.Point(852, 553);
this.lblJump.Name = "lblJump";
this.lblJump.Size = new System.Drawing.Size(44, 18);
this.lblJump.TabIndex = 20;
this.lblJump.Text = "跳至";
//
// txtJump
//
this.txtJump.Location = new System.Drawing.Point(892, 547);
this.txtJump.Name = "txtJump";
this.txtJump.Size = new System.Drawing.Size(60, 28);
this.txtJump.TabIndex = 21;
//
// lblJumpUnit
//
this.lblJumpUnit.AutoSize = true;
this.lblJumpUnit.Location = new System.Drawing.Point(958, 553);
this.lblJumpUnit.Name = "lblJumpUnit";
this.lblJumpUnit.Size = new System.Drawing.Size(26, 18);
this.lblJumpUnit.TabIndex = 22;
this.lblJumpUnit.Text = "页";
//
// btnJump
//
this.btnJump.Location = new System.Drawing.Point(986, 545);
this.btnJump.Name = "btnJump";
this.btnJump.Size = new System.Drawing.Size(80, 34);
this.btnJump.TabIndex = 23;
this.btnJump.Text = "跳转";
this.btnJump.UseVisualStyleBackColor = true;
//
// Form1
//
this.AutoScaleDimensions = new System.Drawing.SizeF(9F, 18F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(1306, 646);
this.Controls.Add(this.btnJump);
this.Controls.Add(this.lblJumpUnit);
this.Controls.Add(this.txtJump);
this.Controls.Add(this.lblJump);
this.Controls.Add(this.btnLast);
this.Controls.Add(this.btnNext);
this.Controls.Add(this.lblPage);
this.Controls.Add(this.btnPrev);
this.Controls.Add(this.btnFirst);
this.Controls.Add(this.lblPageSizeUnit);
this.Controls.Add(this.cboPageSize);
this.Controls.Add(this.lblPageSize);
this.Controls.Add(this.btnClear);
this.Controls.Add(this.btnQuery);
this.Controls.Add(this.btnDelete);
this.Controls.Add(this.btnUpdate);
this.Controls.Add(this.btnAdd);
this.Controls.Add(this.txtAge);
this.Controls.Add(this.lblAge);
this.Controls.Add(this.txtName);
this.Controls.Add(this.lblName);
this.Controls.Add(this.txtId);
this.Controls.Add(this.lblId);
this.Controls.Add(this.dataGridView1);
this.Name = "Form1";
this.Text = "用户管理";
((System.ComponentModel.ISupportInitialize)(this.dataGridView1)).EndInit();
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private System.Windows.Forms.DataGridView dataGridView1;
private System.Windows.Forms.Label lblId;
private System.Windows.Forms.TextBox txtId;
private System.Windows.Forms.Label lblName;
private System.Windows.Forms.TextBox txtName;
private System.Windows.Forms.Label lblAge;
private System.Windows.Forms.TextBox txtAge;
private System.Windows.Forms.Button btnAdd;
private System.Windows.Forms.Button btnUpdate;
private System.Windows.Forms.Button btnDelete;
private System.Windows.Forms.Button btnQuery;
private System.Windows.Forms.Button btnClear;
private System.Windows.Forms.Label lblPageSize;
private System.Windows.Forms.ComboBox cboPageSize;
private System.Windows.Forms.Label lblPageSizeUnit;
private System.Windows.Forms.Button btnFirst;
private System.Windows.Forms.Button btnPrev;
private System.Windows.Forms.Label lblPage;
private System.Windows.Forms.Button btnNext;
private System.Windows.Forms.Button btnLast;
private System.Windows.Forms.Label lblJump;
private System.Windows.Forms.TextBox txtJump;
private System.Windows.Forms.Label lblJumpUnit;
private System.Windows.Forms.Button btnJump;
}
}
后端代码:
cs
using FreeSql;
using System;
using System.Collections.Generic;
using System.Linq.Expressions;
using System.Windows.Forms;
namespace _2
{
public partial class Form1 : Form
{
// ==================== 分页 / 排序状态 ====================
private int _pageSize = 10; // 每页条数(可切换)
private int _page = 1; // 当前页码
private long _totalPages = 1; // 总页数(跳转时校验用)
private string _sortField = "Id"; // 排序字段:Id / Name / Age
private bool _sortAsc = true; // 升序?
private bool _initializing = true; // 初始化期间屏蔽每页条数事件
public Form1()
{
InitializeComponent();
BindEvents();
InitGrid();
InitPaging();
SeedIfEmpty(); // 首次运行插演示数据,正式项目可删
_initializing = false;
LoadData();
}
// ==================== 初始化 ====================
private void BindEvents()
{
btnAdd.Click += btnAdd_Click;
btnUpdate.Click += btnUpdate_Click;
btnDelete.Click += btnDelete_Click;
btnQuery.Click += btnQuery_Click;
btnClear.Click += btnClear_Click;
btnFirst.Click += btnFirst_Click;
btnPrev.Click += btnPrev_Click;
btnNext.Click += btnNext_Click;
btnLast.Click += btnLast_Click;
btnJump.Click += btnJump_Click;
txtJump.KeyDown += txtJump_KeyDown;
cboPageSize.SelectedIndexChanged += cboPageSize_SelectedIndexChanged;
dataGridView1.CellClick += dataGridView1_CellClick;
dataGridView1.ColumnHeaderMouseClick += dataGridView1_ColumnHeaderMouseClick;
}
private void InitGrid()
{
dataGridView1.ReadOnly = true;
dataGridView1.AutoGenerateColumns = true;
dataGridView1.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
dataGridView1.MultiSelect = false;
dataGridView1.AllowUserToAddRows = false;
dataGridView1.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill;
dataGridView1.ColumnHeadersDefaultCellStyle.Font =
new System.Drawing.Font(dataGridView1.Font, System.Drawing.FontStyle.Bold);
}
private void InitPaging()
{
cboPageSize.DropDownStyle = ComboBoxStyle.DropDownList;
cboPageSize.Items.AddRange(new object[] { "10", "20", "50", "100" });
cboPageSize.SelectedIndex = 0; // 默认 10 条
}
private void SeedIfEmpty()
{
if (FreeSqlHelper.Count<User>() > 0) return;
FreeSqlHelper.AddRange(new List<User>
{
new User { Name = "张三", Age = 20 },
new User { Name = "李四", Age = 25 },
new User { Name = "王五", Age = 31 },
new User { Name = "赵六", Age = 18 },
new User { Name = "钱七", Age = 45 },
new User { Name = "孙八", Age = 33 },
new User { Name = "周九", Age = 27 },
new User { Name = "吴十", Age = 52 },
new User { Name = "郑一", Age = 19 },
new User { Name = "王一", Age = 38 },
new User { Name = "冯二", Age = 44 },
new User { Name = "陈三", Age = 29 }
});
}
// ==================== 查询条件 / 排序表达式 ====================
private Expression<Func<User, bool>> BuildWhere()
{
string name = txtName.Text.Trim();
int? age = ParseAge();
if (name.Length > 0 && age.HasValue)
{
int ageValue = age.Value;
return a => a.Name.Contains(name) && a.Age == ageValue;
}
if (name.Length > 0)
{
return a => a.Name.Contains(name);
}
if (age.HasValue)
{
int ageValue = age.Value;
return a => a.Age == ageValue;
}
return null;
}
/// <summary>按当前排序状态生成排序委托(服务端排序,不是只排当前页)</summary>
private Func<ISelect<User>, ISelect<User>> BuildOrder()
{
if (_sortField == "Name")
{
if (_sortAsc) return s => s.OrderBy(a => a.Name);
return s => s.OrderByDescending(a => a.Name);
}
if (_sortField == "Age")
{
if (_sortAsc) return s => s.OrderBy(a => a.Age);
return s => s.OrderByDescending(a => a.Age);
}
if (_sortAsc) return s => s.OrderBy(a => a.Id);
return s => s.OrderByDescending(a => a.Id);
}
private int? ParseAge()
{
int v;
if (int.TryParse(txtAge.Text.Trim(), out v)) return v;
return null;
}
private PageResult<User> QueryPage(int page)
{
return FreeSqlHelper.GetPage<User>(page, _pageSize, BuildWhere(), BuildOrder());
}
// ==================== 加载数据 ====================
private void LoadData()
{
var result = QueryPage(_page);
// 删到最后一页没数据时,自动往前退一页
if (result.TotalPages > 0 && result.Page > result.TotalPages)
{
_page = result.TotalPages;
result = QueryPage(_page);
}
_totalPages = result.TotalPages;
dataGridView1.DataSource = result.Items;
ApplyHeader("Id", "ID", 15);
ApplyHeader("Name", "姓名", 45);
ApplyHeader("Age", "年龄", 20);
lblPage.Text = result.Total == 0
? "暂无数据"
: "第 " + result.Page + "/" + result.TotalPages + " 页,共 " + result.Total + " 条 排序:"
+ SortText();
btnFirst.Enabled = result.HasPrev;
btnPrev.Enabled = result.HasPrev;
btnNext.Enabled = result.HasNext;
btnLast.Enabled = result.HasNext;
}
/// <summary>设置列标题、列宽、排序模式,并在当前排序列上显示 ▲/▼</summary>
private void ApplyHeader(string propName, string title, int fillWeight)
{
if (!dataGridView1.Columns.Contains(propName)) return;
var col = dataGridView1.Columns[propName];
col.SortMode = DataGridViewColumnSortMode.Programmatic; // 排序由我们自己发 SQL,禁止客户端排序
col.FillWeight = fillWeight;
col.HeaderText = title + (propName == _sortField ? (_sortAsc ? " ▲" : " ▼") : "");
}
private string SortText()
{
string name = _sortField == "Id" ? "ID" : (_sortField == "Name" ? "姓名" : "年龄");
return name + (_sortAsc ? " ↑" : " ↓");
}
// ==================== 增 ====================
private void btnAdd_Click(object sender, EventArgs e)
{
string name;
int age;
if (!ValidateInput(out name, out age)) return;
try
{
FreeSqlHelper.Add(new User { Name = name, Age = age });
MessageBox.Show("新增成功");
ClearInput();
_page = 1;
LoadData();
}
catch (Exception ex)
{
MessageBox.Show("新增失败:" + ex.Message);
}
}
// ==================== 改 ====================
private void btnUpdate_Click(object sender, EventArgs e)
{
var current = CurrentUser();
if (current == null)
{
MessageBox.Show("请先在表格里选中要修改的行");
return;
}
string name;
int age;
if (!ValidateInput(out name, out age)) return;
try
{
FreeSqlHelper.Update<User>()
.Set(a => a.Name, name)
.Set(a => a.Age, age)
.Where(a => a.Id == current.Id)
.ExecuteAffrows();
MessageBox.Show("修改成功");
LoadData();
}
catch (Exception ex)
{
MessageBox.Show("修改失败:" + ex.Message);
}
}
// ==================== 删 ====================
private void btnDelete_Click(object sender, EventArgs e)
{
var current = CurrentUser();
if (current == null)
{
MessageBox.Show("请先在表格里选中要删除的行");
return;
}
var confirm = MessageBox.Show("确定删除 [" + current.Name + "] 吗?", "确认删除",
MessageBoxButtons.YesNo, MessageBoxIcon.Question);
if (confirm != DialogResult.Yes) return;
try
{
FreeSqlHelper.DeleteEntity(current);
MessageBox.Show("删除成功");
ClearInput();
LoadData();
}
catch (Exception ex)
{
MessageBox.Show("删除失败:" + ex.Message);
}
}
// ==================== 查询 / 清空 ====================
private void btnQuery_Click(object sender, EventArgs e)
{
_page = 1; // 条件变了,回到第一页
LoadData();
}
private void btnClear_Click(object sender, EventArgs e)
{
ClearInput();
_page = 1;
LoadData();
}
// ==================== 排序 ====================
private void dataGridView1_ColumnHeaderMouseClick(object sender, DataGridViewCellMouseEventArgs e)
{
if (e.ColumnIndex < 0) return;
string prop = dataGridView1.Columns[e.ColumnIndex].DataPropertyName;
if (string.IsNullOrEmpty(prop)) return;
if (prop != "Id" && prop != "Name" && prop != "Age") return;
if (_sortField == prop)
{
_sortAsc = !_sortAsc; // 点同一列,切换升降序
}
else
{
_sortField = prop; // 换列,默认升序
_sortAsc = true;
}
_page = 1;
LoadData();
}
// ==================== 分页:首页 / 上一页 / 下一页 / 末页 ====================
private void btnFirst_Click(object sender, EventArgs e)
{
if (_page == 1) return;
_page = 1;
LoadData();
}
private void btnPrev_Click(object sender, EventArgs e)
{
if (_page <= 1) return;
_page--;
LoadData();
}
private void btnNext_Click(object sender, EventArgs e)
{
if (_page >= _totalPages) return;
_page++;
LoadData();
}
private void btnLast_Click(object sender, EventArgs e)
{
if (_totalPages <= 0) return;
_page = (int)_totalPages;
LoadData();
}
// ==================== 分页:跳转 ====================
private void btnJump_Click(object sender, EventArgs e)
{
DoJump();
}
private void txtJump_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Enter)
{
e.SuppressKeyPress = true; // 不要 "叮" 一声
DoJump();
}
}
private void DoJump()
{
long target;
if (!long.TryParse(txtJump.Text.Trim(), out target))
{
MessageBox.Show("请输入要跳转的页码");
txtJump.Focus();
return;
}
if (_totalPages <= 0)
{
MessageBox.Show("当前没有数据");
return;
}
if (target < 1 || target > _totalPages)
{
MessageBox.Show("页码超出范围,当前共 " + _totalPages + " 页");
txtJump.Focus();
return;
}
_page = (int)target;
LoadData();
txtJump.Clear();
}
// ==================== 每页条数 ====================
private void cboPageSize_SelectedIndexChanged(object sender, EventArgs e)
{
if (_initializing) return;
int v;
if (!int.TryParse(cboPageSize.Text, out v) || v <= 0) return;
_pageSize = v;
_page = 1; // 每页条数变了,从第一页看
LoadData();
}
// ==================== 选中行回填 ====================
private void dataGridView1_CellClick(object sender, DataGridViewCellEventArgs e)
{
if (e.RowIndex < 0) return;
var u = dataGridView1.Rows[e.RowIndex].DataBoundItem as User;
if (u == null) return;
txtId.Text = u.Id.ToString();
txtName.Text = u.Name;
txtAge.Text = u.Age.ToString();
}
// ==================== 辅助 ====================
private User CurrentUser()
{
if (dataGridView1.CurrentRow == null) return null;
return dataGridView1.CurrentRow.DataBoundItem as User;
}
private bool ValidateInput(out string name, out int age)
{
name = txtName.Text.Trim();
age = 0;
if (name.Length == 0)
{
MessageBox.Show("请输入姓名");
txtName.Focus();
return false;
}
if (name.Length > 50)
{
MessageBox.Show("姓名不能超过 50 个字符");
txtName.Focus();
return false;
}
if (!int.TryParse(txtAge.Text.Trim(), out age) || age < 0 || age > 150)
{
MessageBox.Show("年龄请填写 0~150 之间的整数");
txtAge.Focus();
return false;
}
return true;
}
private void ClearInput()
{
txtId.Text = "";
txtName.Text = "";
txtAge.Text = "";
txtName.Focus();
}
}
}
第五步:运行代码,调试程序



到这一步恭喜你,成功学会了FreeSQL框架的使用!!!!!
你在C#程序设计的技能又进了一步!!!