Loading

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

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

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

posted @ 2019-09-22 23:53  BruceNeter  阅读(423)  评论(0编辑  收藏  举报