EFBaseDal

public class BaseDal<T> where T : class, new()
    {
        DataModelContainer db = new DataModelContainer();

/// <summary>
        /// 条件查询
        /// </summary>
        /// <param name="where"></param>
        /// <returns></returns>
        public IQueryable<T> GetEntities(Expression<Func<T, bool>> where)
        {
            return db.Set<T>().Where(where).AsQueryable();
        }

/// <summary>
        /// 分页查询
        /// </summary>
        /// <typeparam name="S"></typeparam>
        /// <param name="pageSize"></param>
        /// <param name="pageIndex"></param>
        /// <param name="count"></param>
        /// <param name="where"></param>
        /// <param name="orderBy"></param>
        /// <param name="isAsc"></param>
        /// <returns></returns>
        public IQueryable<T> GetPageEntities<S>(int pageSize, int pageIndex, out int count, Expression<Func<T, bool>> where, Expression<Func<T, S>> orderBy, bool isAsc)
        {
            count = db.Set<T>().Where(where).Count();
            if (isAsc)
            {
                var temp = db.Set<T>().Where(where).OrderBy<T, S>(orderBy).Skip(pageSize).Take(pageSize * (pageIndex - 1)).AsQueryable();
                return temp;
            }
            else
            {
                var temp = db.Set<T>().Where(where).OrderByDescending<T, S>(orderBy).Skip(pageSize).Take(pageSize * (pageIndex - 1)).AsQueryable();
                return temp;
            }
        }
        /// <summary>
        /// 增加
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        public T Add(T entity)
        {
            db.Set<T>().Add(entity);
            db.SaveChanges();
            return entity;
        }

/// <summary>
        /// 修改
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        public bool Update(T entity)
        {
            db.Entry(entity).State = EntityState.Modified;
            return db.SaveChanges() > 0;

}
        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        public bool Delete(T entity)
        {
            db.Entry(entity).State = EntityState.Deleted;
            return db.SaveChanges() > 0;
        }
    }

时间: 2024-11-05 11:56:20

EFBaseDal的相关文章