EF简单增删改查与分页

 1 /// <summary>
 2 /// 分页查询
 3  /// </summary>
 4 /// <typeparam name="T">要操作的数据类型</typeparam>
 5 /// <param name="whereLambda">Where条件语句</param>
 6 /// <param name="orderLambda">按什么条件排序</param>
 7  /// <param name="pageSize">每页都少条数据</param>
 8 /// <param name="pageIndex">要查询第几页</param>
 9   /// <returns>返回一个泛型集合</returns>
10  static List<T> GetPageList<T>(Func<T, bool> whereLambda, Func<T, object> orderLambda, int pageSize,
11   int pageIndex) where T : class
12    {
13          MyDBEntities context = new MyDBEntities();  
14          var list =  context.Set<T>().Where(whereLambda).OrderBy(orderLambda).Skip((pageIndex - 1) * pageSize).Take(pageSize);
15          return list.ToList();
16  }
View Code

 

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();
        }
    }
posted @ 2017-02-27 16:20  吾蒸笼  阅读(244)  评论(0编辑  收藏  举报