Data Access Layer EntityFramework classical base class - CRUD

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 = to true ; // modify deleted 
            IF (commitNow)
                 the await _db.SaveChangesAsync (); 
        } 
        // /  <Summary> 
        /// check all without being deleted
         ///  </ Summary> 
        ///  <Returns> </ Returns> 
        public IQueryable <T> GetAll () 
        { 
            return _db.Set <T> (). AsNoTracking () the 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();
        }
    }
}

The actual data is modified to delete a property, based on this property to determine whether the check out, a real project, there should be no operation to delete data in the database.

Guess you like

Origin www.cnblogs.com/qwqwQAQ/p/11570055.html