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] ...
随机推荐
- ByteBuffer 字节缓冲区
HeapByteBuffer 在jvm堆上面的一个buffer,底层的本质是一个数组 由于内容维护在jvm里,所以把内容写进buffer里速度会快些:并且,可以更容易回收 DirectB ...
- webpack 从 0 到 1 构建 vue
前端领域框架百花齐放,各种优秀框架出现(react,Vue,ag)等等框架.为了方便开发者快速开发, 开发对应的 cli 脚手架,来提高产出.然而初中级的前端工程师对项目里的 webpack 封装和配 ...
- Tomcat--启动慢
本篇为转载文章 来自:https://www.cnblogs.com/user-sunli/articles/13917035.html 有时启动Tomcat,发现启动很慢,需要几分钟,这个问题值得重 ...
- mysql--read only
问题背景: 1.在进行数据迁移和从库只读状态设置时,都会涉及到只读状态和Master-Slave主从关系设置 2.数据库参数文件默认是只读,重启数据库服务时 解决方法: 1.在my.cnf配置文件中添 ...
- 备忘 springboot 整合ehcache,注入CacheManager时提示 required a bean of type 'org.springframework.cache.CacheManager' that could not be found
问题因人而异,此处仅做备忘 整合过程: 1.添加maven依赖 <dependency> <groupId>net.sf.ehcache</groupId> < ...
- Educational Codeforces Round 106 (Rated for Div. 2) 简单题解(A~C)
1499A. Domino on Windowsill 题意:给定一个 \(2 \times n\) 的空间,\(k1.k2 行要设置为白色(2 \times 1)\) 然后其他的设置为黑色 思路:为 ...
- Educational Codeforces Round 6 620E. New Year Tree(DFS序+线段树)
题目链接:点击打开链接 题意:给你一棵树,编号1~n,告诉你根结点是1. 每次有两个操作: 1,将以v为根的子树的结点全部染成颜色c 2,问以v为根的紫书的结点的颜色种类. 思路:如果这是一条线段的话 ...
- Android 3分钟带你入门开发测试
作者:Zhu Yifei 作为一名合格的开发人员,基本的开发测试能力必不可少,开发测试分单元测试和UI测试,通过开发测试可以减少开发人员自测时间,提升开发质量.本篇文章可以帮助初级开发人员快速了解开发 ...
- el-date-picker 组件时间格式化方式
1 <el-form-item label="安放龙骨时间"> 2 <el-date-picker 3 v-model="baseInfoForm.se ...
- [吉他谱]duvet