第六篇 專案疑問 ------- BaseService where T : class, new() 含義
阿新 • • 發佈:2019-02-08
public abstract class BaseService<T> where T : class, new() { //當前倉儲 //DbSession的存放 //為了職責單一的原則,將獲取執行緒內唯一例項的DbSession的邏輯放到工廠裡面去了 public IDbSession DbSession = DbSessionFactory.GetCurrentDbSession(); //基類的建構函式 protected BaseService() { SetCurrentRepository(); //建構函式裡面去呼叫了,此設定當前倉儲的抽象方法 } public IBaseRepository<T> CurrentRepository { get; set; } public abstract void SetCurrentRepository(); //子類必須實現 //實現對資料庫的新增功能 public T AddEntity(T entity) { //呼叫T對應的倉儲來做新增工作 T addEntity = CurrentRepository.AddEntity(entity); DbSession.SaveChanges(); return addEntity; } //實現對資料的修改功能 public bool UpdateEntity(T entity) { CurrentRepository.UpdateEntity(entity); return DbSession.SaveChanges() > 0; } //實現對資料庫的刪除功能 public bool DeleteEntity(T entity) { CurrentRepository.DeleteEntity(entity); return DbSession.SaveChanges() > 0; } //實現對資料庫的查詢 --簡單查詢 public IQueryable<T> LoadEntities(Expression<Func<T, bool>> whereLambda) { return CurrentRepository.LoadEntities(whereLambda); } //實現對資料庫的查詢 --簡單查詢 public IQueryable<T> LoadEntities() { return CurrentRepository.LoadEntities(); } /// <summary> /// 實現對資料的分頁查詢 /// </summary> /// <typeparam name="S">按照某個類進行排序</typeparam> /// <param name="pageIndex">當前第幾頁</param> /// <param name="pageSize">一頁顯示多少條資料</param> /// <param name="total">總條數</param> /// <param name="whereLambda">取得排序的條件</param> /// <param name="isAsc">如何排序,根據倒敘還是升序</param> /// <param name="orderByLambda">根據那個欄位進行排序</param> /// <returns></returns> public IQueryable<T> LoadPageEntities<S>(int pageIndex, int pageSize, out int total, Expression<Func<T, bool>> whereLambda, bool isAsc, Expression<Func<T, S>> orderByLambda) { return CurrentRepository.LoadPageEntities(pageIndex, pageSize, out total, whereLambda, isAsc, orderByLambda); } } }
查詢後發現這是型別引數約束,.NET支援的型別引數約束有以下五種: