1. 程式人生 > >EFCore中增刪改查的方法

EFCore中增刪改查的方法

public class EFDao<T> : IDao<T> where T : class
    {
        private EnergyIotDbContext db;

        public EFDao(EnergyIotDbContext _db)
        {
            db = _db;
        }

        public async Task<bool> Add(T Entity)
        {

            //老寫法
            //db.Entry(Entity).State = EntityState.Added;
            await db.Set<T>().AddAsync(Entity);
            return await db.SaveChangesAsync() > 0;
        }

        public async Task<bool> Delete(T Entity)
        {
            //老寫法
            //db.Set<T>().Attach(Entity);
            //db.Entry(Entity).State = EntityState.Deleted;
            //新寫法
            db.Set<T>().Remove(Entity);
            return await db.SaveChangesAsync() > 0;
        }

        public async Task<bool> Update(T Entity)
        {
            //老寫法
            //db.Set<T>().Attach(Entity);
            //db.Entry(Entity).State = EntityState.Modified;
            //新寫法
            db.Set<T>().Update(Entity);
            return await db.SaveChangesAsync() > 0;
        }

        public IEnumerable<T> GetEntities(Expression<Func<T, bool>> exp)
        {
            //var data = db.Set<T>().Find()
            return CompileQuery(exp);
        }

        public IEnumerable<T> GetEntitiesForPaging(int Page, int pageSize, Expression<Func<T, bool>> exp)
        {
            return CompileQuery(exp).Skip((Page - 1) * pageSize).Take(pageSize);
        }

        public T GetEntity(Expression<Func<T, bool>> exp)
        {
            return CompileQuerySingle(exp);
        }

        private IEnumerable<T> CompileQuery(Expression<Func<T, bool>> exp)
        {
            var func = EF.CompileQuery((EnergyIotDbContext context, Expression<Func<T, bool>> exps) => context.Set<T>().Where(exp));
            return func(db, exp);
        }
        private T CompileQuerySingle(Expression<Func<T, bool>> exp)
        {
            var func = EF.CompileQuery((EnergyIotDbContext context, Expression<Func<T, bool>> exps) => context.Set<T>().FirstOrDefault(exp));
            return func(db, exp);
        }
    }

很久以前分享過ef4.0 5.0的寫法 但是在efcore裡更簡單了不需要跟蹤實體狀態了我們可以F12看下他定義的方法

我們可以看到 Add Update Remove 方法使用起來更簡單靈活了