C# EF通用DAL基类


    public abstract class BaseDal<T> where T : class, new()
    {
        #region 查
        public List<T> All()
        {
            using (var db = new DBEntities())
            {
                return db.Set<T>().ToList<T>();
            }
        }

        public List<T> Query(Func<T, bool> func)
        {
            using (var db = new DBEntities())
            {
                return db.Set<T>().Where(func).ToList<T>();
            }
        }
        #endregion

        #region 增
        public T Add(T entity)
        {
            using (var db = new DBEntities())
            {
                db.Entry(entity).State = EntityState.Added;
                db.SaveChanges();
                return entity;
            }
        }

        public bool Add(List<T> entities)
        {
            using (var db = new DBEntities())
            {
                db.Entry(entities).State = EntityState.Added;
                return db.SaveChanges() > 0;
            }
        }
        #endregion

        #region 删
        public bool Del(T entity)
        {
            using (var db = new DBEntities())
            {
                db.Set<T>().Attach(entity);
                db.Entry(entity).State = EntityState.Deleted;
                return db.SaveChanges() > 0;
            }
        }

        public bool Del(List<T> entities)
        {
            using (var db = new DBEntities())
            {
                foreach (var entity in entities)
                {
                    db.Set<T>().Attach(entity);
                    db.Entry(entity).State = EntityState.Deleted;
                }
                return db.SaveChanges() > 0;
            }
        }

        public bool Del(Func<T, bool> func)
        {
            using (var db = new DBEntities())
            {
                var entities = Query(func);
                return Del(entities);
            }
        }
        #endregion

        #region 改
        public bool Update(T entity)
        {

            using (var db = new DBEntities())
            {
                db.Set<T>().Attach(entity);
                db.Entry(entity).State = EntityState.Modified;
                return db.SaveChanges() > 0;
            }
        }
        #endregion 
    }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值