使用EF框架的增刪改查和分頁的公共類


public class BaseRepository<T> where T : class { //實例化EF框架 DataModelContainer db = new DataModelContainer(); //添加 public T AddEntities(T entity) { db.Entry<T>(entity).State = EntityState.Added; db.SaveChanges(); return entity; } //修改 public bool UpdateEntities(T entity) { db.Set<T>().Attach(entity); db.Entry<T>(entity).State = EntityState.Modified; return db.SaveChanges() > 0; } //刪除 public bool DeleteEntities(T entity) { db.Set<T>().Attach(entity); db.Entry<T>(entity).State = EntityState.Deleted; return db.SaveChanges() > 0; } //查詢 public IQueryable<T> LoadEntities(Func<T, bool> wherelambda) { return db.Set<T>().Where<T>(wherelambda).AsQueryable(); } //分頁 public IQueryable<T> LoadPagerEntities<S>(int pageSize, int pageIndex, out int total, Func<T, bool> whereLambda, bool isAsc, Func<T, S> orderByLambda) { var tempData = db.Set<T>().Where<T>(whereLambda); total = tempData.Count(); //排序獲取當前頁的數據 if (isAsc) { tempData = tempData.OrderBy<T, S>(orderByLambda). Skip<T>(pageSize * (pageIndex - 1)). Take<T>(pageSize).AsQueryable(); } else { tempData = tempData.OrderByDescending<T, S>(orderByLambda). Skip<T>(pageSize * (pageIndex - 1)). Take<T>(pageSize).AsQueryable(); } return tempData.AsQueryable(); } }


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM