一、 为什么需要代码生成工具?
在传统开发中,手动编写数据库实体类、DAO层、Winform界面代码往往耗时且容易出错。SqlSugar作为国产优秀ORM框架,结合代码生成工具(如Database2Sharp、SoEasyPlatform),能将开发效率提升300%+!
二、核心工具选择与环境准备
1. 工具链组合推荐
工具名称 | 作用 | 特点 |
---|---|---|
SqlSugar | ORM框架 | 支持多数据库,轻量级,易扩展 |
Database2Sharp | 代码生成器 | 支持Winform/ASP.NET项目生成 |
Visual Studio 2022 | 开发环境 | .NET Framework 4.8支持 |
2. 环境配置步骤
# 安装Visual Studio 2022(需包含.NET桌面开发工作负载)
# 下载SqlSugar ORM包(NuGet安装)
Install-Package SqlSugar -Version 6.1.5
# 下载代码生成工具(以Database2Sharp为例)
# 官网地址:https://www.database2sharp.com
三、代码生成器实战:从数据库到Winform项目
1. 数据库设计与准备
-- 示例:员工管理表
CREATE TABLE Employees (
Id INT PRIMARY KEY IDENTITY(1,1),
Name NVARCHAR(100) NOT NULL,
Age INT,
Department NVARCHAR(50),
HireDate DATETIME
);
2. 生成SqlSugar项目代码
步骤1:配置代码生成器
// Database2Sharp配置示例
public class GeneratorConfig {
public string ConnectionString { get; set; } = "Server=127.0.0.1;Database=TestDB;User ID=sa;Password=123456;";
public DbType DbType { get; set; } = DbType.SqlServer;
public string OutputPath { get; set; } = @"D:\Projects\SqlSugarDemo";
public bool GenerateWinform { get; set; } = true;
public bool GenerateCoreLayer { get; set; } = true;
}
// 执行生成命令
var config = new GeneratorConfig();
CodeGenerator.Run(config); // 生成完整项目结构
生成的项目结构
SqlSugarDemo/
├── SugarProjectCore/ # 核心服务层
│ ├── Interfaces/ # 接口定义
│ ├── Models/ # 实体类
│ └── Services/ # 业务逻辑
├── SugarProjectWin/ # Winform界面层
│ ├── Forms/ # 窗体文件
│ ├── Controls/ # 自定义控件
│ └── App.config # 配置文件
└── References/ # 依赖库
3. Winform界面代码详解
示例:员工管理窗体
// EmployeesForm.cs
public partial class EmployeesForm : Form {
private readonly EmployeeService _employeeService;
public EmployeesForm() {
InitializeComponent();
_employeeService = new EmployeeService(); // 依赖注入
}
/// <summary>
/// 加载数据到DataGridView
/// </summary>
private void LoadData() {
var employees = _employeeService.GetAll(); // 调用服务层方法
dataGridView1.DataSource = employees;
}
/// <summary>
/// 新增按钮点击事件
/// </summary>
private void btnAdd_Click(object sender, EventArgs e) {
var form = new EmployeeEditForm();
if (form.ShowDialog() == DialogResult.OK) {
_employeeService.Insert(form.Employee); // 插入数据
LoadData();
}
}
/// <summary>
/// 删除选中记录
/// </summary>
private void btnDelete_Click(object sender, EventArgs e) {
if (dataGridView1.SelectedRows.Count > 0) {
var id = (int)dataGridView1.SelectedRows[0].Cells["Id"].Value;
_employeeService.Delete(id); // 调用删除方法
LoadData();
}
}
}
4. 服务层实现与SqlSugar集成
示例:EmployeeService.cs
public class EmployeeService {
private readonly ISqlSugarClient _db;
public EmployeeService() {
_db = new SqlSugarClient(new ConnectionConfig {
ConnectionString = ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString,
DbType = DbType.SqlServer,
IsAutoCloseConnection = true,
InitKeyType = InitKeyType.Attribute
});
}
/// <summary>
/// 获取所有员工信息
/// </summary>
public List<Employee> GetAll() {
return _db.Queryable<Employee>().ToList();
}
/// <summary>
/// 插入新员工
/// </summary>
public int Insert(Employee employee) {
return _db.Insertable(employee).ExecuteReturnIdentity();
}
/// <summary>
/// 删除员工
/// </summary>
public int Delete(int id) {
return _db.Deleteable<Employee>().Where(u => u.Id == id).ExecuteCommand();
}
}
四、高级功能扩展
1. 分页查询与条件过滤
/// <summary>
/// 分页查询员工
/// </summary>
public PagedList<Employee> GetPaged(int pageIndex, int pageSize, string department = null) {
var query = _db.Queryable<Employee>();
if (!string.IsNullOrEmpty(department)) {
query = query.Where(u => u.Department == department); // 动态条件
}
int totalCount;
var result = query.ToPageList(pageIndex, pageSize, out totalCount);
return new PagedList<Employee> {
Data = result,
TotalCount = totalCount
};
}
2. 事务处理与复杂操作
/// <summary>
/// 批量导入员工数据
/// </summary>
public void BatchImport(List<Employee> employees) {
_db.Ado.BeginTran(); // 开启事务
try {
foreach (var employee in employees) {
_db.Insertable(employee).ExecuteCommand();
}
_db.Ado.CommitTran(); // 提交事务
} catch (Exception ex) {
_db.Ado.RollbackTran(); // 回滚事务
throw new ApplicationException("批量导入失败", ex);
}
}
五、性能优化与安全策略
1. 缓存机制集成
/// <summary>
/// 缓存部门列表
/// </summary>
private List<Department> _departmentCache;
public List<Department> GetDepartments() {
if (_departmentCache == null) {
_departmentCache = _db.Queryable<Department>()
.ToList()
.Cache(30 * 60); // 缓存30分钟
}
return _departmentCache;
}
2. 安全校验与权限控制
/// <summary>
/// 删除员工(带权限校验)
/// </summary>
public int Delete(int id, string currentUser) {
// 检查当前用户是否有权限
if (!_permissionService.HasPermission(currentUser, "Employee_Delete")) {
throw new UnauthorizedAccessException("无删除权限");
}
return _db.Deleteable<Employee>().Where(u => u.Id == id).ExecuteCommand();
}
六、部署与维护技巧
1. 一键打包发布
# 使用MSBuild打包Winform项目
msbuild /p:Configuration=Release /p:Platform=x86 SqlSugarDemo.sln
# 生成安装包(使用Inno Setup)
"C:\Program Files (x86)\Inno Setup 6\ISCC.exe" setup.iss
2. 日志与异常监控
// 全局异常处理(Program.cs)
[STAThread]
static void Main() {
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
// 注册全局异常处理
Application.ThreadException += (sender, e) => {
MessageBox.Show($"发生错误: {e.Exception.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
File.WriteAllText("error.log", e.Exception.ToString()); // 写入日志
};
Application.Run(new MainForm());
}