SqlSugar的Repository
1、仓储说明
仓储可以让你的方法更加的规范,需要什么方法都封装到仓储中,下次就能重复使用,并且能很好的和你业务拆分开
这种设计模式简单粗暴用起来也方便 ,文章下面有可以运行的DEMO
2、仓储方法
仓储有一套自带的数据库操作方法,比起 db.xx.xxx来说可能更简便些满足一些常用需求, 复杂的功能还是用db.xxx.xxx
//查询var data1 = base.GetById(1);//根据id查询var data2 = base.GetList();//查询所有 (FindList)var data3 = base.GetList(it => it.Id == 1); //TOP1条件var data4 = base.GetSingle(it => it.Id == 1);//查询单条记录,结果集不能超过1,不然会提示错误var data= base.GetFirst(it => it.Id == 1);//查询第一条记录var p = new PageModel() { PageIndex = 1, PageSize = 2 };var data5 = base.GetPageList(it => it.Name == "xx", p);Console.Write(p.PageCount);var data6 = base.GetPageList(it => it.Name == "xx", p, it => it.Name, OrderByType.Asc);Console.Write(p.PageCount);List<IConditionalModel> conModels = new List<IConditionalModel>();conModels.Add(new ConditionalModel(){FieldName="id",ConditionalType=ConditionalType.Equal,FieldValue="1"});//id=1var data7 = base.GetPageList(conModels, p, it => it.Name, OrderByType.Asc);var data8 = base.AsQueryable().Where(x => x.Id == 1).ToList();//使用Queryable//插入base.Insert(insertObj);base.InsertRange(InsertObjs);var id = base.InsertReturnIdentity(insertObj);//插入返回自增var SnowflakeId=base.InsertReturnSnowflakeId(insertObj);//插入返回雪花IDbase.AsInsertable(insertObj).ExecuteCommand();//复杂功能使用Insertable//删除base.Delete(T);//实体删除 需要有主键base.Delete(List<T>);//集合删除 需要有主键base.DeleteById(1);base.DeleteByIds(new object [] { 1, 2 }); //数组带是 ids方法 ,封装传 object [] 类型//技巧 int [] 转换成 object[] 写法:ids.Cast<object>().ToArray()base.Delete(it => it.Id == 1);base.AsDeleteable().Where(it => it.Id == 1).ExecuteCommand();//复杂功能用 Deleteable//实体方式更新更新base.Update(insertObj); base.UpdateRange(InsertObjs); base.AsUpdateable(insertObj).UpdateColumns(it=>new { it.Name }).ExecuteCommand();//复杂功能用 Updateable //表达式方式更新base.Update(it => new Order() { Name = "a" /*可以多列*/ }, it => it.Id == 1); //只更新name 并且id=1base.UpdateSetColumnsTrue(it=>new Order(){ Name = "a" }, it =>it.Id == 1);//更新name+过滤事件赋值字段 base.AsUpdateable().SetColumns(it=>new Order{ Name="a" }) .Where(it=>it.Id==1).ExecuteCommand();//复杂功能用 Updateable //高级操作base.Context //获取db对象base.AsSugarClient // 获取完整的db对象base.AsTenant // 获取多库相关操作//如果Context是子Dbbase.Context.Root//可以用Root拿主Dbbase.Context.Root.AsTenant()//拿到租户对象//切换仓储 (可以注入多个仓储取代,这样就不用切换了)base.ChangeRepository<Repository<OrderItem>>() //多租户用法有区别:https://www.donet5.com/Home/Doc?typeId=2405base.Change<OrderItem>()//只支持自带方法和单库 |
3、创建仓储
3.1 创建仓储
只需要几行代码就搞定了,我们定义的Repository是公用类,不能包含具体的类务逻辑,即使不使用扩展方法自带的方法也够开发
public class Repository<T> : SimpleClient<T> where T : class, new(){ public Repository(ISqlSugarClient db) { base.Context=db; } /// <summary> /// 扩展方法,自带方法不能满足的时候可以添加新方法 /// </summary> /// <returns></returns> public List<T> CommQuery(string json) { //base.Context.Queryable<T>().ToList();可以拿到SqlSugarClient 做复杂操作 return null; } } |
4、使用仓储
4.1 通过IOC使用仓储
//注入仓储builder.Services.AddScoped(typeof(Repository<>));//注入SqlSugar ...省略,不会看入门//多个可以在构造函数写多个(用这种方式就不需要切换仓储了,有几个注入几个)public WeatherForecastController(Repository<Order> repOrder,Repository<Custom> repCustom){ _repOrder= repOrder; _repCustom=repCustom;}//使用注入的仓储_repOrder.Insert(data);_repOrder.Context.Queryable<T>().ToList();//.Context可以拿到db对象 //创建的仓储 public class Repository<T> : SimpleClient<T> where T : class, new(){ public Repository(ISqlSugarClient db)//因为不需要切换仓储所以可以直接用构造函数获取db { base.Context=db; }} |
4.2 不用IOC使用仓储
//该用例建议升级5.1.3.35以上版本 public class UserService : IUserService, IDynamicApiController, ITransient//接口根据业务可以不需要 { //也可以用Ioc注入,不注入更方便些( ”=>" 表示用的时候才去new,不会在实例化类时候去new Repository<Abpusers> _userRepository => new Repository<Abpusers>();//Repository不能单例 ISqlSugarClient _db=>_userRepository.Context; /// <summary> /// 获取用户列表 /// </summary> /// <returns></returns> public async Task<List<GetUserDto>> Get() { var users = await _userRepository.GetListAsync(); return users.Adapt<List<GetUserDto>>(); } } public class Repository<T> : SimpleClient<T> where T : class, new(){ public Repository() { base.Context=DbHelper.GetDbInstance() }} |
注意:因为支持获取外部仓储,所以不需要像ABP那样构造函数写一堆
//获取外部仓储var itemDal=_userRepository.ChangeRepository<Repository<OrderItem>>();var orderDal=_userRepository.ChangeRepository<Repository<Order>>();//base.Change<OrderItem>()这种写法与上面区别在于只能用ORM中的方法,没办法使用扩展类中的方法 |
DEMO下载:
SqlSugarDemo.rar
4.3 db直接调用仓储
//使用ORM自带的仓储var orderDal= db.GetSimpleClient<Order>();//使用自定义的仓储 5.1.3.28-preview06var orderDal=db.GetRepository<Repository<Order>>();//3.1有介绍自定义仓储如创建//使用仓储方法orderDal.Insert(data); |
5、调用外部仓储
操作Order表的同时,我还想使用OrderItem这个仓储怎么办?
var orderItemDb = _userRepository.ChangeRepository<Repository<OrderItem>>();public Repository(ISqlSugarClient db==null)//这儿要改成可空{ base.Context=db; } //如果是多库模式需要注入,打开面页看标题4//https://www.donet5.com/Home/Doc?typeId=2405 |
6、仓储中使用事务
注意: 如果是多租户事务写法有差异,看标题7
try { _userRepository.AsTenant().BeginTran(); //你的增查改方法 _userRepository.AsTenant().CommitTran(); } catch (Exception ex) { _userRepository.AsTenant().RollbackTran(); throw; } |
注意: 如果是多租户事务写法有差异,看标题7
7、多租户使用仓储
因为要多个仓储用一个SqlSugarClient,我们需要用到Sugar.Ioc进行DB共享
https://www.donet5.com/Home/Doc?typeId=2405

浙公网安备 33010602011771号