BaseDAL数据层基类1
/// <summary> /// EF数据库操作基类 /// </summary> /// <typeparam name="T"></typeparam> public partial class BaseDAL<T> where T : class, new() { private DbContext dbContext = DbContextFactory.Create(); #region 1.Add /// <summary> /// 增加一条数据 /// </summary> /// <param name="t"></param> public void Add(T t) { dbContext.Set<T>().Add(t); } /// <summary> /// 同时增加多条数据到一张表(事务处理) /// </summary> /// <param name="entitys"></param> /// <returns></returns> public bool AddEntity(List<T> entitys) { foreach (var entity in entitys) { dbContext.Entry<T>(entity).State = EntityState.Added; } // entitys.ForEach(c=>db.Entry<T>(c).State = EntityState.Added);//等价于上面的循环 return dbContext.SaveChanges() > 0; } #endregion /// <summary> /// 删除一条数据 /// </summary> /// <param name="t"></param> public void Delete(T t) { dbContext.Set<T>().Remove(t); } /// <summary> /// 修改一条数据 /// </summary> /// <param name="t"></param> public void Update(T t) { dbContext.Set<T>().AddOrUpdate(t); } /// <summary> /// 获取一条数据 /// </summary> /// <param name="whereLambda"></param> /// <returns></returns> public IQueryable<T> GetModels(Expression<Func<T, bool>> whereLambda) { return dbContext.Set<T>().Where(whereLambda); } /// <summary> /// 获取分页数据 /// </summary> /// <typeparam name="type">类型</typeparam> /// <param name="pageSize"></param> /// <param name="pageIndex"></param> /// <param name="isAsc"></param> /// <param name="OrderByLambda"></param> /// <param name="WhereLambda"></param> /// <returns></returns> public IQueryable<T> GetModelsByPage<type>(int pageSize, int pageIndex, bool isAsc, Expression<Func<T, type>> OrderByLambda, Expression<Func<T, bool>> WhereLambda) { //是否升序 if (isAsc) { return dbContext.Set<T>().Where(WhereLambda).OrderBy(OrderByLambda).Skip((pageIndex - 1) * pageSize).Take(pageSize); } else { return dbContext.Set<T>().Where(WhereLambda).OrderByDescending(OrderByLambda).Skip((pageIndex - 1) * pageSize).Take(pageSize); } } /// <summary> /// 统一保存 /// </summary> /// <returns></returns> public bool SaveChanges() { return dbContext.SaveChanges() > 0; }