一、Sqlsugar简介
1.性能上有很大优势
sqlsugar是性能最好的ORM之一,具有超越Dapper的性能 ,走的是EMIT够构中间语言动态编译到程序集,完成高性能的实体绑定,达到原生水平。
2.功能非常强大
除了EF以外可以说的是功能最大的ORM框架
支持 DbFirst、CodeFirst、数据库维护、链式查询、链式更新、链式删除、链式插入、实体属性、复杂模型的查询、ADO.NET。特别是批量等功能都是货真价实的并非循环操作。
SqlSugar 4.0版本 6月底支持SqlSever的Core版 ,预计7月份支持多库,8月分开始分布式ORM的开发。 (3.x版本已经支持了4种数据库,相对稳定功能简单)
3.语法简单
完美的语法,可以秒杀现有所有ORM框架
二、主要介绍的是如何使用结合mysql数据库使用Sqlsugar
1.新建解决方案,自定义解决方案名称和保存路径
2.此时我们需要添加三个包,首先找到工具 =》NuGet包管理器 =>管理解决方案的NuGet程序包
3.依次添加以下三个程序包
Newtonsoft.Json:要注意最好添加较高版本的,否则会有兼容性问题
Sqlsugar:这个版本要根据你的.Net Framework的版本选择你合适的版本,这里我用的是.Net Framework4.5所以我安装的是sqlsugar5.0.0.8
MySql.Data
4.准备工作已经做完了,现在可以开始正文了
先贴一段代码,这个是我封装的一个操作数据库的一个类,我采用的是单例模式,不过有个弊端就是不能使用高并发的情况
public class DBContext where T : class, new()
{
public SqlSugarClient Db;
private static DBContext mSingle = null;
public static DBContext GetInstance()
{
if (mSingle == null)
mSingle = new DBContext();
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 CurrentDb { get { return new SimpleClient(Db); } }
///
/// 获取所有
///
///
public virtual List GetList()
{
return CurrentDb.GetList();
}
///
/// 根据表达式查询
///
///
public virtual List GetList(Expression> whereExpression)
{
return CurrentDb.GetList(whereExpression);
}
///
/// 根据表达式查询分页
///
///
public virtual List GetPageList(Expression> whereExpression, PageModel pageModel)
{
return CurrentDb.GetPageList(whereExpression, pageModel);
}
///
/// 根据表达式查询分页并排序
///
/// it
///
/// it=>it.id或者it=>new{it.id,it.name}
/// OrderByType.Desc
///
public virtual List GetPageList(Expression> whereExpression, PageModel pageModel, Expression> orderByExpression = null, OrderByType orderByType = OrderByType.Asc)
{
return CurrentDb.GetPageList(whereExpression, pageModel, orderByExpression, orderByType);
}
///
/// 根据主键查询
///
///
public virtual List GetById(dynamic id)
{
return CurrentDb.GetById(id);
}
///
/// 根据主键删除
///
///
///
public virtual bool Delete(dynamic id)
{
if (string.IsNullOrEmpty(id.ObjToString))
{
Console.WriteLine(string.Format("要删除的主键id不能为空值!"));
}
return CurrentDb.Delete(id);
}
///
/// 根据实体删除
///
///
///
public virtual bool Delete(T data)
{
if (data == null)
{
Console.WriteLine(string.Format("要删除的实体对象不能为空值!"));
}
return CurrentDb.Delete(data);
}
///
/// 根据主键删除
///
///
///
public virtual bool Delete(dynamic[] ids)
{
if (ids.Count() <= 0)
{
Console.WriteLine(string.Format("要删除的主键ids不能为空值!"));
}
return CurrentDb.AsDeleteable().In(ids).ExecuteCommand() > 0;
}
///
/// 根据表达式删除
///
///
///
public virtual bool Delete(Expression> whereExpression)
{
return CurrentDb.Delete(whereExpression);
}
///
/// 根据实体更新,实体需要有主键
///
///
///
public virtual bool Update(T obj)
{
if (obj == null)
{
Console.WriteLine(string.Format("要更新的实体不能为空,必须带上主键!"));
}
return CurrentDb.Update(obj);
}
///
///批量更新
///
///
///
public virtual bool Update(List objs)
{
if (objs.Count <= 0)
{
Console.WriteLine(string.Format("要批量更新的实体不能为空,必须带上主键!"));
}
return CurrentDb.UpdateRange(objs);
}
///
/// 插入
///
///
///
public virtual bool Insert(T obj)
{
return CurrentDb.Insert(obj);
}
///
/// 批量
///
///
///
public virtual bool Insert(List 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.GetInstance().CurrentDb.Insert(b))
{
Console.WriteLine("books_添加成功!");
}
if (DBContext.GetInstance().Db.Insertable(bt).ExecuteCommand() > 0)
{
Console.WriteLine("BookType_添加成功!");
}
例子到这里就结束了,分享一下,我在做这个过程中遇到的问题:
1.因为我原本项目中已经存在程序包Newtonsoft.Json,而它的版本较低,当时忽略了版本问题,导致版本不兼容问题。后面升级之后就可以了。
2.犹豫项目需要高并发处理数据,所以我上边写的单例模式其实存在一定的问题,所以做了一定的修改,代码贴一下
public class DBContext where T : class, new()
{
public SqlSugarClient Db;
///
/// 修改后的代码
///
///
public static DBContext OpDB()
{
DBContext dbcontext_t = new DBContext();
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 CurrentDb { get { return new SimpleClient(Db); } }
//可以扩展更多方法
}
ok,该demo的分享就到这了,如果有什么错误的地方欢迎指出,有不理解的也可以留言。
作者:Tulip123