ORM框架SqlSugarCore详细教程
1为什么使用sqlsugarcore:
SqlSugar一款轻量级,高性能,支持.Net4.+和ASP.Net Core的一款ORM框架。
对我而言 他可以生成数据库表模板 可以自己配置模板的参数 在项目中更简单的直接调用 带有自定义的快捷查询语句
2添加一个modelbuild启动的控制台应用程序 我习惯用分层写 主要是为了生成model到web解决方案中
2.1 添加一个控制台应用程序
2.2 引用sqlsugarcore Nuget包
2.3 在program中编写映射实体模型的方法
class Program
{
static void Main(string[] args)
{
//实体生成的路径
var modelpath = @"SqlSugarCoreDemo\Models";
var path = Directory.GetCurrentDirectory();
path = path.Substring(0, path.IndexOf(@"\bin"));
//声明实体生成的绝对路径
path = path.Substring(0, path.LastIndexOf(@"\") + 1) + modelpath;
var db = new SqlSugarClient(new ConnectionConfig()
{
//连接字符串
ConnectionString = @"Integrated Security=SSPI;Persist Security Info=False;User ID=sa;Initial Catalog=LocalDB;Data Source=.",
//连接的数据库的类型
DbType = DbType.SqlServer,
IsAutoCloseConnection = true,
InitKeyType = InitKeyType.Attribute
});
//获取所有表
List<DbTableInfo> list = db.DbMaintenance.GetTableInfoList();
//获取所有视图
List<DbTableInfo> viewList = db.DbMaintenance.GetViewInfoList();
var allList = list.Concat(viewList);
//循环所有的表和视图 他们属于同一个类 DbTableInfo
foreach (DbTableInfo table in allList)
{
//首字母转大写
string table_name = table.Name.Substring(0, 1).ToUpper() + table.Name.Substring(1);
//映射表增加 实体名称 和表名称
db.MappingTables.Add(table_name, table.Name);
//根据表名 获取表所有的字段
List<DbColumnInfo> dd = db.DbMaintenance.GetColumnInfosByTableName(table.Name);
foreach (DbColumnInfo item in dd)
{
//映射字段添加 (字段名,字段名,表名)
db.MappingColumns.Add(item.DbColumnName, item.DbColumnName, table_name);
}
db.DbFirst.
SettingClassTemplate(old =>
{
return old;
//这里是自定义的模板 当你定义模板时 请注意格式的缩减距离 要不然会导致生成的模板格式很奇怪
// return GetClassTemplate();
})
.SettingNamespaceTemplate(old =>
{
return old;
})
.SettingPropertyDescriptionTemplate(old =>
{
return old;
//这里是自定义的模板
//return GetPropertyDescriptionTemplate();
})
.SettingPropertyTemplate(old =>
{
return old;
})
.SettingConstructorTemplate(old =>
{
return old;
}).IsCreateAttribute().Where(table.Name).CreateClassFile(path, "ZSCQYQSJPT.Web.Models");
}
}
/// <summary>
/// 这是自定义的命名空间的模板
/// </summary>
/// <returns></returns>
static string GetClassTemplate()
{
return @"
{using}
namespace {Namespace}
{
{ClassDescription}{SugarTable}
public partial class {ClassName}:ModelContext
{
public {ClassName}()
{
{Constructor}}{PropertyName}}
}";
}
/// <summary>
/// 这是自定义的字段的模板
/// </summary>
/// <returns></returns>
static string GetPropertyDescriptionTemplate()
{
return @"
/// <summary>
/// Remark:{PropertyDescription}
/// Default:{DefaultValue}
/// Nullable:{IsNullable}
/// </summary>";
}
}
2.4 我们启动控制台应用程序
2.5 可以看到我们program中配置的路径已经生成了相应的模板
3 在web程序中调用sqlSugarcore操作数据库
3.1 首先创建一个web应用程序 API还是MVC都可 注意Nuget包引用sqlsugarcore
3.2 创建一个类 主要是用于连接数据库的类 它会作为后续增删改查的sql帮助类的基类
public class DbContext
{
public SqlSugarClient db;
public DbContext()
{
if (db == null)
{
db = new SqlSugarClient(new ConnectionConfig()
{
ConnectionString = "Integrated Security=SSPI;Persist Security Info=False;User ID=sa;Initial Catalog=LocalDB;Data Source=.",//必填, 数据库连接字符串
DbType = DbType.SqlServer, //必填, 数据库类型
IsAutoCloseConnection = true, //默认false, 时候知道关闭数据库连接, 设置为true无需使用using或者Close操作
InitKeyType = InitKeyType.SystemTable //默认SystemTable, 字段信息读取, 如:该属性是不是主键,是不是标识列等等信息
});
}
}
}
3.3 然后创建一个帮助类 主要是对Local表在sqlsugarcore框架下的增删改查 需要继承DbContext 因为到时候控制器直接调用Helpservices 会执行基类DbContext 的构造函数 并对数据库 SqlSugarClient db赋值。用于直接操作数据库。
public class Helpservices : DbContext
{
/// <summary>
/// 增加
/// </summary>
/// <param name="model"></param>
/// <returns></returns>
public bool AddAsync(Local model)
{
return db.Insertable(model).ExecuteCommand() > 0;
}
/// <summary>
/// 批量删除
/// </summary>
/// <param name="Llist"></param>
/// <returns></returns>
public async Task<bool> DeleteAsync(List<Local> Llist)
{
var result = true;
db.Ado.BeginTran();
try
{
foreach (var item in Llist)
{
if (await db.Deleteable(item).ExecuteCommandAsync() >= 0)
{
result = true;
}
}
}
catch (Exception)
{
result = false;
}
if (result)
{
db.Ado.CommitTran();
}
else
{
db.Ado.RollbackTran();
}
return result;
}
/// <summary>
/// 查询列表
/// </summary>
/// <param name="model"></param>
/// <returns></returns>
public List<Local> ListAsync(Local model)
{
var result = db.Queryable<Local>().Where(w => w.sendtime == "ajfhjah").OrderBy("status desc").ToList();
return result;
}
/// <summary>
/// 查询单条信息
/// </summary>
/// <param name="model"></param>
/// <returns></returns>
public Local SingleAsync(Local model)
{
return db.Queryable<Local>().Single(it => it.ID == model.ID);
}
/// <summary>
/// 修改
/// </summary>
/// <param name="model"></param>
/// <returns></returns>
public bool UpdateAsync(Local model)
{
return db.Updateable(model).UpdateColumns(it => new { it.sendtime, it.backtime, it.status }).Where(it => it.ID == model.ID).ExecuteCommand() > 0;
}
}
3.4 实操 在控制器中调用
下面是我实操的数据库类
///<summary>
///
///</summary>
[SugarTable("Local")]
public partial class Local
{
public Local()
{
}
/// <summary>
/// Desc:
/// Default:
/// Nullable:False
/// </summary>
[SugarColumn(IsPrimaryKey = true)]
public Guid ID { get; set; }
/// <summary>
/// Desc:
/// Default:
/// Nullable:True
/// </summary>
public string sendtime { get; set; }
/// <summary>
/// Desc:
/// Default:
/// Nullable:True
/// </summary>
public string backtime { get; set; }
/// <summary>
/// Desc:
/// Default:
/// Nullable:True
/// </summary>
public int? status { get; set; }
}
下面是具体实操调用内容
Helpservices helpservices = new Helpservices();
//增加
Local local = new Local();
local.ID = Guid.NewGuid();
local.sendtime = "ajfhjah";
local.backtime = "ryey";
local.status = 46;
var result = helpservices.AddAsync(local);
//查单条
Guid id = new Guid("0d6c0f7c-685a-4bb2-8de1-37f7be6c5832");
var singlocal = helpservices.SingleAsync(new Local { ID = id });
//查列表
var listlocal = helpservices.ListAsync(new Local { });
//修改
var updatelocal = helpservices.UpdateAsync(new Local { ID = id, sendtime = "我是测试1", backtime = "我是测试2", status = 32 });
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】博客园社区专享云产品让利特惠,阿里云新客6.5折上折
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· DeepSeek 解答了困扰我五年的技术问题
· 为什么说在企业级应用开发中,后端往往是效率杀手?
· 用 C# 插值字符串处理器写一个 sscanf
· Java 中堆内存和栈内存上的数据分布和特点
· 开发中对象命名的一点思考
· DeepSeek 解答了困扰我五年的技术问题。时代确实变了!
· PPT革命!DeepSeek+Kimi=N小时工作5分钟完成?
· What?废柴, 还在本地部署DeepSeek吗?Are you kidding?
· 赶AI大潮:在VSCode中使用DeepSeek及近百种模型的极简方法
· DeepSeek企业级部署实战指南:从服务器选型到Dify私有化落地