SqlSugar的Repository

1、仓储说明

仓储可以让你的方法更加的规范,需要什么方法都封装到仓储中,下次就能重复使用,并且能很好的和你业务拆分开

这种设计模式简单粗暴用起来也方便 ,文章下面有可以运行的DEMO

2、仓储方法

仓储有一套自带的数据库操作方法,比起 db.xx.xxx来说可能更简便些满足一些常用需求, 复杂的功能还是用db.xxx.xxx

//查询vardata1 = base.GetById(1);//根据id查询vardata2 = base.GetList();//查询所有 (FindList)vardata3 = base.GetList(it => it.Id == 1); //TOP1条件vardata4 = base.GetSingle(it => it.Id == 1);//查询单条记录,结果集不能超过1,不然会提示错误vardata= base.GetFirst(it => it.Id == 1);//查询第一条记录varp = newPageModel() { PageIndex = 1, PageSize = 2 };vardata5 = base.GetPageList(it => it.Name == "xx", p);Console.Write(p.PageCount);vardata6 = base.GetPageList(it => it.Name == "xx", p, it => it.Name, OrderByType.Asc);Console.Write(p.PageCount);List conModels = newList();conModels.Add(newConditionalModel(){FieldName="id",ConditionalType=ConditionalType.Equal,FieldValue="1"});//id=1vardata7 = base.GetPageList(conModels, p, it => it.Name, OrderByType.Asc);vardata8 = base.AsQueryable().Where(x => x.Id == 1).ToList();//使用Queryable//插入base.Insert(insertObj);base.InsertRange(InsertObjs);varid = base.InsertReturnIdentity(insertObj);//插入返回自增varSnowflakeId=base.InsertReturnSnowflakeId(insertObj);//插入返回雪花IDbase.AsInsertable(insertObj).ExecuteCommand();//复杂功能使用Insertable//删除base.Delete(T);//实体删除 需要有主键base.Delete(List);//集合删除 需要有主键base.DeleteById(1);base.DeleteByIds(newobject[] { 1, 2 }); //数组带是 ids方法 ,封装传 object [] 类型//技巧 int [] 转换成 object[]  写法:ids.Cast().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 => newOrder() { Name = "a"/*可以多列*/}, it => it.Id == 1); //只更新name 并且id=1base.UpdateSetColumnsTrue(it=>newOrder(){ Name = "a"}, it =>it.Id == 1);//更新name+过滤事件赋值字段 base.AsUpdateable().SetColumns(it=>newOrder{  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>() //多租户用法有区别:https://www.donet5.com/Home/Doc?typeId=2405base.Change()//只支持自带方法和单库

3、创建仓储

3.1 创建仓储

只需要几行代码就搞定了,我们定义的Repository是公用类,不能包含具体的类务逻辑,即使不使用扩展方法自带的方法也够开发

publicclassRepository : SimpleClient whereT : class, new(){    publicRepository(ISqlSugarClient db)    {                 base.Context=db;     }    ///     /// 扩展方法,自带方法不能满足的时候可以添加新方法    ///     ///     publicList CommQuery(stringjson)    {       //base.Context.Queryable().ToList();可以拿到SqlSugarClient 做复杂操作       returnnull;    }    }

4、使用仓储

4.1 通过IOC使用仓储

//注入仓储builder.Services.AddScoped(typeof(Repository<>));//注入SqlSugar ...省略,不会看入门//多个可以在构造函数写多个(用这种方式就不需要切换仓储了,有几个注入几个)publicWeatherForecastController(Repository repOrder,Repository repCustom){     _repOrder= repOrder;     _repCustom=repCustom;}//使用注入的仓储_repOrder.Insert(data);_repOrder.Context.Queryable().ToList();//.Context可以拿到db对象 //创建的仓储 publicclassRepository : SimpleClient whereT : class, new(){    publicRepository(ISqlSugarClient db)//因为不需要切换仓储所以可以直接用构造函数获取db    {        base.Context=db;      }}

4.2 不用IOC使用仓储

 //该用例建议升级5.1.3.35以上版本 publicclassUserService : IUserService, IDynamicApiController, ITransient//接口根据业务可以不需要 {        //也可以用Ioc注入,不注入更方便些( ”=>" 表示用的时候才去new,不会在实例化类时候去new         Repository _userRepository => newRepository();//Repository不能单例        ISqlSugarClient _db=>_userRepository.Context;        ///         /// 获取用户列表        ///         ///         publicasync Task> Get()        {            varusers = await _userRepository.GetListAsync();            returnusers.Adapt>();        }  } publicclassRepository : SimpleClient whereT : class, new(){    publicRepository()     {      base.Context=DbHelper.GetDbInstance()          }}

注意:因为支持获取外部仓储,所以不需要像ABP那样构造函数写一堆

//获取外部仓储varitemDal=_userRepository.ChangeRepository>();varorderDal=_userRepository.ChangeRepository>();//base.Change()这种写法与上面区别在于只能用ORM中的方法,没办法使用扩展类中的方法

4.3 db直接调用仓储

//使用ORM自带的仓储varorderDal= db.GetSimpleClient();//使用自定义的仓储  5.1.3.28-preview06varorderDal=db.GetRepository>();//3.1有介绍自定义仓储如创建//使用仓储方法orderDal.Insert(data);

5、调用外部仓储

操作Order表的同时,我还想使用OrderItem这个仓储怎么办?

varorderItemDb = _userRepository.ChangeRepository>();publicRepository(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共享