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=1
var 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);//插入返回雪花ID
base.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=1
base.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是子Db
base.Context.Root//可以用Root拿主Db
base.Context.Root.AsTenant()//拿到租戶對象
 
 
//切換倉儲 (可以注入多個倉儲取代,這樣就不用切換了)
base.ChangeRepository<Repository<OrderItem>>() //多租戶用法有區別:https://www.donet5.com/Home/Doc?typeId=2405
base.Change<OrderItem>()//只支持自帶方法和單庫

 

3、創建倉儲

3.1 創建倉儲

只需要幾行代碼就搞定了,我們定義的Repository是公用類,不能包含具體的類務邏輯,即使不使用擴展方法自帶的方法也夠開發

public class Repository<T> : SimpleClient<T> where T : classnew()
{
    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 : classnew()
{
    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 : classnew()
{
    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-preview06
var 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

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章