EntityFramework经典数据访问层基类——增删改查

namespace StudentSys.DAL
{
    public class BaseService:IDisposable where T:BaseEntity,new()
    {
        protected readonly StudentContext _db;
        public BaseService(StudentContext studentContext)
        {
            _db = studentContext;
        }
        /// 
        /// 增加
        /// 
        /// 
        /// 是否立即提交
        /// 
        public async Task CreateAsync(T t,bool commitNow=true)
        {
            _db.Set().Add(t);
            if (commitNow)
                await _db.SaveChangesAsync();
        }
        /// 
        /// 修改
        /// 
        /// 
        /// 
        /// 
        public async Task ModifyAsync(T t,bool commitNow = true)
        {
            _db.Entry(t).State = System.Data.Entity.EntityState.Modified;
            if (commitNow)
                await _db.SaveChangesAsync();
        }
        /// 
        /// 删除
        /// 
        /// 用户ID
        /// 
        /// 
        public async Task DeleteAsync(Guid id, bool commitNow = true)
        {
            T t = new T
            {
                Id = id,
            };
            _db.Entry(t).State = System.Data.Entity.EntityState.Unchanged;
            t.IsRemove = true;//修改为已删除
            if (commitNow)
                await _db.SaveChangesAsync();
        }
        /// 
        /// 查所有的没有被删除的
        /// 
        /// 
        public IQueryable GetAll()
        {
            return _db.Set().AsNoTracking().Where(m => !m.IsRemove);
        }
        /// 
        /// 根据ID查找
        /// 
        /// 
        public async Task GetAsync(Guid id)
        {
            return await GetAll().FirstAsync(m => m.Id == id);
        }
        public void Dispose()
        {
            _db.Dispose();
        }
    }
}

删除实际是修改数据的某属性,根据此属性判断是否查询出来,一个真正的项目,不应该存在删除数据库数据的操作。

转载于:https://www.cnblogs.com/qwqwQAQ/p/11570055.html

你可能感兴趣的:(EntityFramework经典数据访问层基类——增删改查)