一对儿程序猿 2020-04-09
sqlsugar是性能最好的ORM之一,具有超越Dapper的性能 ,走的是EMIT够构中间语言动态编译到程序集,完成高性能的实体绑定,达到原生水平。
2.功能非常强大
除了EF以外可以说的是功能最大的ORM框架
支持 DbFirst、CodeFirst、数据库维护、链式查询、链式更新、链式删除、链式插入、实体属性、复杂模型的查询、ADO.NET。特别是批量等功能都是货真价实的并非循环操作。
SqlSugar 4.0版本 6月底支持SqlSever的Core版 ,预计7月份支持多库,8月分开始分布式ORM的开发。 (3.x版本已经支持了4种数据库,相对稳定功能简单)
完美的语法,可以秒杀现有所有ORM框架
详细语法请看孙凯旋博客园 http://www.codeisbug.com/Doc/8
Newtonsoft.Json:要注意最好添加较高版本的,否则会有兼容性问题
Sqlsugar:这个版本要根据你的.Net Framework的版本选择你合适的版本,这里我用的是.Net Framework4.5所以我安装的是sqlsugar5.0.0.8
MySql.Data
先贴一段代码,这个是我封装的一个操作数据库的一个类,我采用的是单例模式,不过有个弊端就是不能使用高并发的情况
public class DBContext<T> where T : class, new() { public SqlSugarClient Db; private static DBContext<T> mSingle = null; public static DBContext<T> GetInstance() { if (mSingle == null) mSingle = new DBContext<T>(); return mSingle; } protected DBContext() { //通过这个可以直接连接数据库 Db = new SqlSugarClient(new ConnectionConfig() { //可以在连接字符串中设置连接池pooling=true;表示开启连接池 //eg:min pool size=2;max poll size=4;表示最小连接池为2,最大连接池是4;默认是100 ConnectionString = "database=‘" + "BookShop" + "‘;Data Source = ‘" + "127.0.0.1" + "‘; User Id = ‘" + "root" + "‘; pwd=‘" + "1234" + "‘;charset=‘utf8‘;pooling=true", DbType = SqlSugar.DbType.MySql,//我这里使用的是Mysql数据库 IsAutoCloseConnection = true,//自动关闭连接 InitKeyType = InitKeyType.Attribute }); //调式代码 用来打印SQL //Db.Aop.OnLogExecuting = (sql, pars) => //{ // Console.WriteLine(sql + "\r\n" + // Db.Utilities.SerializeObject(pars.ToDictionary(it => it.ParameterName, it => it.Value))); // Console.WriteLine(); //}; } public void Dispose() { if (Db != null) { Db.Dispose(); } } public SimpleClient<T> CurrentDb { get { return new SimpleClient<T>(Db); } } /// <summary> /// 获取所有 /// </summary> /// <returns></returns> public virtual List<T> GetList() { return CurrentDb.GetList(); } /// <summary> /// 根据表达式查询 /// </summary> /// <returns></returns> public virtual List<T> GetList(Expression<Func<T, bool>> whereExpression) { return CurrentDb.GetList(whereExpression); } /// <summary> /// 根据表达式查询分页 /// </summary> /// <returns></returns> public virtual List<T> GetPageList(Expression<Func<T, bool>> whereExpression, PageModel pageModel) { return CurrentDb.GetPageList(whereExpression, pageModel); } /// <summary> /// 根据表达式查询分页并排序 /// </summary> /// <param name="whereExpression">it</param> /// <param name="pageModel"></param> /// <param name="orderByExpression">it=>it.id或者it=>new{it.id,it.name}</param> /// <param name="orderByType">OrderByType.Desc</param> /// <returns></returns> public virtual List<T> GetPageList(Expression<Func<T, bool>> whereExpression, PageModel pageModel, Expression<Func<T, object>> orderByExpression = null, OrderByType orderByType = OrderByType.Asc) { return CurrentDb.GetPageList(whereExpression, pageModel, orderByExpression, orderByType); } /// <summary> /// 根据主键查询 /// </summary> /// <returns></returns> public virtual List<T> GetById(dynamic id) { return CurrentDb.GetById(id); } /// <summary> /// 根据主键删除 /// </summary> /// <param name="id"></param> /// <returns></returns> public virtual bool Delete(dynamic id) { if (string.IsNullOrEmpty(id.ObjToString)) { Console.WriteLine(string.Format("要删除的主键id不能为空值!")); } return CurrentDb.Delete(id); } /// <summary> /// 根据实体删除 /// </summary> /// <param name="id"></param> /// <returns></returns> public virtual bool Delete(T data) { if (data == null) { Console.WriteLine(string.Format("要删除的实体对象不能为空值!")); } return CurrentDb.Delete(data); } /// <summary> /// 根据主键删除 /// </summary> /// <param name="id"></param> /// <returns></returns> public virtual bool Delete(dynamic[] ids) { if (ids.Count() <= 0) { Console.WriteLine(string.Format("要删除的主键ids不能为空值!")); } return CurrentDb.AsDeleteable().In(ids).ExecuteCommand() > 0; } /// <summary> /// 根据表达式删除 /// </summary> /// <param name="id"></param> /// <returns></returns> public virtual bool Delete(Expression<Func<T, bool>> whereExpression) { return CurrentDb.Delete(whereExpression); } /// <summary> /// 根据实体更新,实体需要有主键 /// </summary> /// <param name="id"></param> /// <returns></returns> public virtual bool Update(T obj) { if (obj == null) { Console.WriteLine(string.Format("要更新的实体不能为空,必须带上主键!")); } return CurrentDb.Update(obj); } /// <summary> ///批量更新 /// </summary> /// <param name="id"></param> /// <returns></returns> public virtual bool Update(List<T> objs) { if (objs.Count <= 0) { Console.WriteLine(string.Format("要批量更新的实体不能为空,必须带上主键!")); } return CurrentDb.UpdateRange(objs); } /// <summary> /// 插入 /// </summary> /// <param name="id"></param> /// <returns></returns> public virtual bool Insert(T obj) { return CurrentDb.Insert(obj); } /// <summary> /// 批量 /// </summary> /// <param name="id"></param> /// <returns></returns> public virtual bool Insert(List<T> objs) { return CurrentDb.InsertRange(objs); } //可以扩展更多方法 }
5.还有就是需要有model类,就是跟数据库中表对应的model类,比如我这里是book和booktype,附加一段代码做个参考
[SugarTable("Books")]//指定数据库中的表名,要对应数据库的表名,否则会出错 public class Books { [SugarColumn(IsPrimaryKey = true, IsIdentity = true)]//指定主键和自动增长 public int Id { get; set; } public int BId { get; set; } public string BName { get; set; } public int TypeId { get; set; } }
6.开始操作数据库了
Books b = new Books() { BId = 2, BName = "西游记", TypeId = 2 }; BookType bt = new BookType() { TId= 3, TName = "健康"}; if (DBContext<Books>.GetInstance().CurrentDb.Insert(b)) { Console.WriteLine("books_添加成功!"); } if (DBContext<BookType>.GetInstance().Db.Insertable(bt).ExecuteCommand() > 0) { Console.WriteLine("BookType_添加成功!"); }
其他操作数据库的例子参考孙凯旋的博客园吧,附链接 http://www.codeisbug.com/Doc/8/1123
例子到这里就结束了,分享一下,我在做这个过程中遇到的问题:
1.因为我原本项目中已经存在程序包Newtonsoft.Json,而它的版本较低,当时忽略了版本问题,导致版本不兼容问题。后面升级之后就可以了。
2.犹豫项目需要高并发处理数据,所以我上边写的单例模式其实存在一定的问题,所以做了一定的修改,代码贴一下
public class DBContext<T> where T : class, new() { public SqlSugarClient Db; /// <summary> /// 修改后的代码 /// </summary> /// <returns></returns> public static DBContext<T> OpDB() { DBContext<T> dbcontext_t = new DBContext<T>(); dbcontext_t.Db = new SqlSugarClient(new ConnectionConfig() { ConnectionString = "database=‘" + "bookshop" + "‘;Data Source = ‘" + "127.0.0.1" + "‘; User Id = ‘" + "root" + "‘; pwd=‘" + "1234" + "‘;charset=‘utf8‘;pooling=true", DbType = SqlSugar.DbType.MySql, IsAutoCloseConnection = true, InitKeyType = InitKeyType.Attribute }); return dbcontext_t; } protected DBContext() { Db = new SqlSugarClient(new ConnectionConfig() { ConnectionString = "database=‘" + "bookshop" + "‘;Data Source = ‘" + "127.0.0.1" + "‘; User Id = ‘" + "root" + "‘; pwd=‘" + "1234" + "‘;charset=‘utf8‘;pooling=true", DbType = SqlSugar.DbType.MySql, IsAutoCloseConnection = true, InitKeyType = InitKeyType.Attribute }); //调式代码 用来打印SQL Db.Aop.OnLogExecuting = (sql, pars) => { Console.WriteLine(sql + "\r\n" + Db.Utilities.SerializeObject(pars.ToDictionary(it => it.ParameterName, it => it.Value))); Console.WriteLine(); }; } public SimpleClient<T> CurrentDb { get { return new SimpleClient<T>(Db); } } //可以扩展更多方法 }