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
SqlSugar的Repository的更多相关文章
- 一步一步创建ASP.NET MVC5程序[Repository+Autofac+Automapper+SqlSugar](四)
前言 上一篇<一步一步创建ASP.NET MVC5程序[Repository+Autofac+Automapper+SqlSugar](三)>,我们完成了: * 引用SqlSugar * ...
- 一步一步创建ASP.NET MVC5程序[Repository+Autofac+Automapper+SqlSugar](三)
前言 上一篇<一步一步创建ASP.NET MVC5程序[Repository+Autofac+Automapper+SqlSugar](二)>我们通过如下操作: 创建实体及工具类 创建Re ...
- 一步一步创建ASP.NET MVC5程序[Repository+Autofac+Automapper+SqlSugar](一)
前言 大家好,我是Rector 从今天开始,Rector将为大家推出一个关于创建ASP.NET MVC5程序[Repository+Autofac+Automapper+SqlSugar]的文章系列, ...
- 一步一步创建ASP.NET MVC5程序[Repository+Autofac+Automapper+SqlSugar](五)
前言 Hi,大家好,我是Rector 时间飞逝,一个星期又过去了,今天还是星期五,Rector在图享网继续跟大家分享系列文本:一步一步创建ASP.NET MVC5程序[Repository+Autof ...
- 一步一步创建ASP.NET MVC5程序[Repository+Autofac+Automapper+SqlSugar](二)
前言: 在本系列第一篇<一步一步创建ASP.NET MVC5程序[Repository+Autofac+Automapper+SqlSugar](一)>中,我为大家介绍了搭建空白解决方案以 ...
- 一步一步创建ASP.NET MVC5程序[Repository+Autofac+Automapper+SqlSugar](六)
前言 大家好,我是Rector 又是星期五,很兴奋,很高兴,很high...啦啦啦... Rector在图享网又和大家见面啦!!!上一篇<一步一步创建ASP.NET MVC5程序[Reposit ...
- 一步一步创建ASP.NET MVC5程序[Repository+Autofac+Automapper+SqlSugar](七)
前言 大家好,我依旧是你们的老朋友Rector,很高兴又在周五的时候准时和大家见面. Rector的系列文章[一步一步创建ASP.NET MVC5程序[Repository+Autofac+Autom ...
- 一步一步创建ASP.NET MVC5程序[Repository+Autofac+Automapper+SqlSugar](八)
前言 Hi, 大家好,还是星期五,还是Rector,又在图享网准时和大家见面了. 今天给大家带来系列教程<一步一步创建ASP.NET MVC5程序[Repository+Autofac+Auto ...
- 一步一步创建ASP.NET MVC5程序[Repository+Autofac+Automapper+SqlSugar](九)
前言 童鞋们,大家好 我是专注.NET开发者社区建设的实践者Rector. 首先,为自己间隔了两个星期五再更新本系列文章找个不充分的理由:Rector最近工作,家庭的各种事务所致,希望大家谅解. 本文 ...
- 一步一步创建ASP.NET MVC5程序[Repository+Autofac+Automapper+SqlSugar](十)
前言 朋友们, 大家好,我还是Rector,写ASP.NET MVC 5系列文章[一步一步创建ASP.NET MVC5程序Repository+Autofac+Automapper+SqlSugar] ...
随机推荐
- 解决ttrss(Tiny Tiny RSS)中fever无法使用的问题
问题描述 在ttrss刚搭建好的时候,进行了如下操作: 随后键入了密码(fever密码) 最后,按照官方给的提示,在Fluent Reader中测试,弹出如下错误信息: 解决方案 复制官方给的链接,删 ...
- 聊聊大语言模型(LLM)的 10 个实际应用
近期,苹果公司正在悄悄研究可以挑战的 OpenAI.谷歌和其他公司的 AI 工具,建立了自己的框架来创建大语言模型,并创建了一个聊天机器人服务,一些工程师称之为"Apple GPT" ...
- 解读IDC《中国视频云市场跟踪》最新报告,视频云将趋向何方?
国际权威咨询公司IDC发布<中国视频云市场跟踪(2021 H2)>报告,阿里云连续四年稳居中国视频云整体市场份额第一,整体市场份额占比达26.9%. 时至2021,中国视频云的数字背后 近 ...
- 记录一次centost docker 容器 占满磁盘100% 的处理
备忘 1.查看系统磁盘使用情况 df -h 2.查看docker镜像及容器空间占比 docker system df 3.查找大文件 find / -type f -size +100M -print ...
- 第十二届蓝桥杯C++B组 A~H题题解
本次题解格式参考 墨羽魂韶 本文所用的试题: 第十二届蓝桥杯大赛软件赛省赛_CB.pdf 最后编辑时间 2021年4月29日 21:27:46 2022 年 4月 8号 15点13分 填空题答案速览 ...
- Tomcat 优雅关闭之路
本文首发于 vivo互联网技术 微信公众号 链接:https://mp.weixin.qq.com/s/ZqkmoAR4JEYr0x0Suoq7QQ作者:马运杰 本文通过阅读Tomcat启动和关闭流程 ...
- redis管道技术pipeline一 ——api
import java.io.UnsupportedEncodingException; import java.util.Set; import org.springframework.beans. ...
- OpenSCA用开源的方式做开源风险治理:Why? What? How?
随着容器.微服务等新技术的快速迭代,开源软件已成为业界主流形态,开源和云原生时代的到来导致软件供应链越来越趋于复杂化和多样化,网络攻击者开始采用软件供应链攻击作为击破关键基础设施的的重要突破口,从而导 ...
- hbulider 运行微信开发者工具 Enable IDE Service (y/N) [27D[27C
问题:hbulider 运行微信开发者工具 出现如下页面,没有输入y的交互界面 解决办法:先安装微信开发者工具,然后打开微信开发者工具 再次运行:
- uni-app图片上传接口联调
https://www.bilibili.com/video/BV1jy4y1B7pw?p=159&spm_id_from=pageDriver