ASP.net MVC 构建layui管理后台(构造基础仓储)<1>

2019/04/10 10:10
阅读数 34

本文章为ASP.net MVC 构建layui管理后台,第一篇。

使用EF+ado.net 实体数据模型模式进行底层的数据库连接。

 

 

 

 在项目添加一个类库Model

 

 

 

 

 

 在类库Model上添加一个ado.net 实体数据模型

 

 

 

 

 

 

 

 

 

 添加成功之后,效果如下

 

 

 

 

 

 

 

按照以上的步骤,已经完成了,对应数据库的连接,关联,下面我们来定义数据库的存储。

在Model类库下新建EFDbContext类,用于连接数据库

/// <summary>
        /// 连接数据库
        /// </summary>
        /// <returns></returns>
        public static ZWSDBEntities GetDbContext()
        {
            ZWSDBEntities dbContext = CallContext.GetData("ZWSDBEntities") as ZWSDBEntities;
            if (dbContext == null)
            {
                dbContext = new ZWSDBEntities();
                CallContext.SetData("ZWSDBEntities", dbContext);
            }
            return dbContext;
        }

其中ZWSDBEntities是每个人的可能不一样,可以在下图中找

 

 

接下来定义两个接口IBaseEntityDAL,IBaseEntityService

/// <summary>
    /// 封装定义数据操作接口
    /// </summary>
    /// <typeparam name="T"></typeparam>
    public interface IBaseEntityDAL<T> where T : class
    {
        //! 检查是否存在持久实体对象
        bool HasInstance(Expression<Func<T, bool>> where);
        bool HasRelevanceInstance<T2>(Expression<Func<T2, bool>> where);

        //! 提取单个对象的方法
        T GetByIntID(int id);
        T GetByStringID(string oid);
        T GetByGuid(Guid oid);
        T GetByLambda(Expression<Func<T, bool>> where);

        //! 根据 id ,提取实例,如果没有,创建一个新的实例,并执行持久化
        T GetOrCreatePersistence(Guid id);
        //! 根据 id ,提取实例,如果没有,创建一个新的实例,但不执行持久化
        T GetOrCreateNotPersistence(Guid id);

        //! 添加对象的方法
        void Add(T bo);
        void AddOrUpdate(T bo, bool isForNewObject, ref int returnPoint);

        //! 删除对象的方法
        void Delete(T bo);
        void DeleteRelevenceObject<T2>(T2 relevanceBo);
        void DeleteRelevenceObjectsByLambda<T2>(Expression<Func<T2, bool>> where);

        //! 更新对象的方法
        void Update(T bo);

        //! 提取对象集合的方法
        IQueryable<T> GetAll();
        IQueryable<T> GetAllOrdered(Expression<Func<T, bool>> order);
        IQueryable<T> GetMany(Expression<Func<T, bool>> where);
        IQueryable<T> GetMany(Expression<Func<T, object>> selector, object val);
        IQueryable<T> GetManyOrdered<TKey>(Expression<Func<T, bool>> where, Expression<Func<T, TKey>> order);
        IQueryable<T> GetAllOrderedPaged<TKey>(Expression<Func<T, TKey>> order, int page, int pageSize, ref int pageAmount, ref int boAmount, ref bool isDesc);
        //IQueryable<T> GetDataPaging(DataTableModel dataTableModel, ref int dataAmount, string orderProperty, Expression<Func<T, bool>> where = null);
        IQueryable<T> GetAllCommonWay(
            ref int pageAmount,
            ref int boAmount,
            Expression<Func<T, bool>> where = null,
            Expression<Func<T, bool>> order = null,
            bool? isDesc = null,
            int? page = null,
            int? pageSize = null);

        //! 数据处理约束管理方法
        bool CanAdd(Expression<Func<T, bool>> where);

        //! 用于处理一些附加对象的方法
        T2 GetRelevanceObject<T2>(Guid id);
        T2 GetRelevanceObject<T2>(Expression<Func<T2, bool>> where);
        T2 GetRelevanceObjectBySqlQuery<T2>(string SqlQureyString);

        IQueryable<T2> GetRelevanceObjects<T2>(Expression<Func<T2, bool>> where);
        IQueryable<T2> GetRelevanceObjects<T2>(
            Expression<Func<T2, bool>> where = null,
            Expression<Func<T2, bool>> order = null,
            bool? isDesc = null);

        void AddRelevanceObject<T2>(T2 relevanceBo);
        void UpdateRelevanceObject<T2>(T2 relevanceBo);
    }
/// <summary>
    /// 封装定义数据操作接口
    /// </summary>
    /// <typeparam name="T"></typeparam>
    public interface IBaseEntityService<T> where T : class
    {
        /// <summary>
        /// 检查是否存在持久实体对象
        /// </summary>
        /// <param name="where"></param>
        /// <returns></returns>
        bool HasInstance(Expression<Func<T, bool>> where);
        bool HasRelevanceInstance<T2>(Expression<Func<T2, bool>> where);


        T GetByIntID(int id);
        /// <summary>
        /// 提取单个对象的方法(ID)
        /// </summary>
        /// <param name="oid">ID</param>
        /// <returns></returns>
        T GetByStringID(string oid);
        /// <summary>
        ///提取单个对象的方法(GID)
        /// </summary>
        /// <param name="oid"></param>
        /// <returns></returns>
        T GetByGuid(Guid oid);
        T GetByLambda(Expression<Func<T, bool>> where);

        //! 根据 id ,提取实例,如果没有,创建一个新的实例,并执行持久化
        T GetOrCreatePersistence(Guid id);
        //! 根据 id ,提取实例,如果没有,创建一个新的实例,但不执行持久化
        T GetOrCreateNotPersistence(Guid id);

        //! 添加对象的方法
        void Add(T bo);
        void AddOrUpdate(T bo, bool isForNewObject, params Expression<Func<T, object>>[] updatedProperties);

        //! 删除对象的方法
        void Delete(T bo);

        void DeleteRelevenceObject<T2>(T2 relevanceBo);
        void DeleteRelevenceObjectsByLambda<T2>(Expression<Func<T2, bool>> where);

        //! 更新对象的方法
        void Update(T bo);

        void Update(T entity, params Expression<Func<T, object>>[] updatedProperties);

        //! 提取对象集合的方法
        IQueryable<T> GetAll();
        IQueryable<T> GetAllOrdered(Expression<Func<T, bool>> order);
        IQueryable<T> GetMany(Expression<Func<T, bool>> where);
        IQueryable<T> GetMany(Expression<Func<T, object>> selector, object val);
        IQueryable<T> GetManyOrdered<TKey>(Expression<Func<T, bool>> where, Expression<Func<T, TKey>> order);

        //! 按照分页方式提取对象集合的方法
        IQueryable<T> GetAllOrderedPaged(string orderProeprtyName, int page, int pageSize, ref int pageAmount, ref int boAmount, ref bool isDesc);
        IQueryable<T> GetAllOrderedPaged<TKey>(Expression<Func<T, TKey>> order, int page, int pageSize, ref int pageAmount, ref int boAmount, ref bool isDesc);

        //IQueryable<T> GetDataPaging(GridPager page, ref int dataAmount, Expression<Func<T, bool>> where = null);
        IQueryable<T> GetManyOrderedPaged<Tkey>(Expression<Func<T, bool>> where, Expression<Func<T, Tkey>> order, int page, int pageSize, ref int pageAmount, ref int boAmount, ref bool isDesc);
        IQueryable<T> GetManyOrderedByProertyNamePaged(Expression<Func<T, bool>> where, string orderProeprtyName, int page, int pageSize, ref int pageAmount, ref int boAmount, ref bool isDesc);
        IQueryable<T> GetAllCommonWay(
            ref int pageAmount,
            ref int boAmount,
            Expression<Func<T, bool>> where = null,
            Expression<Func<T, bool>> order = null,
            bool? isDesc = null,
            int? page = null,
            int? pageSize = null);

        //! 数据处理约束管理方法
        bool CanAdd(Expression<Func<T, bool>> where);

        //! 用于处理一些附加对象的方法
        T2 GetRelevanceObject<T2>(Guid id);
        T2 GetRelevanceObject<T2>(Expression<Func<T2, bool>> where);
        T2 GetRelevanceObjectBySqlQuery<T2>(string SqlQureyString);

        IQueryable<T2> GetRelevanceObjects<T2>(Expression<Func<T2, bool>> where);
        IQueryable<T2> GetRelevanceObjects<T2>(
            Expression<Func<T2, bool>> where = null,
            Expression<Func<T2, bool>> order = null,
            bool? isDesc = null);

        IQueryable<T2> GetManyRelevanceObjectsOrderedByProertyNamePaged<T2>(Expression<Func<T2, bool>> where, string orderProeprtyName, int page, int pageSize, ref int pageAmount, ref int boAmount, ref bool isDesc);

        void AddRelevanceObject<T2>(T2 relevanceBo);
        void UpdateRelevanceObject<T2>(T2 relevanceBo);
    }

两个操作类,BaseEntityDAL,BaseEntityService

/// <summary>
    /// 基于 EF CodeFirst 独立的针对 IBaseEntityService 方法的实现,其实际实现时通过继承的方式处理
    /// 
    /// 实现基础操作方法的基类
    /// </summary>
    public abstract class BaseEntityDAL<T> where T : class
    {
        protected readonly DbContext _Context;
        protected readonly IDbSet<T> _DbSet;

        public BaseEntityDAL(DbContext context)
        {
            this._Context = context;
            _DbSet = _Context.Set<T>();
        }

        /// <summary>
        /// 根据条件检查数据是否已存在
        /// </summary>
        /// <param name="where">Lamda表达式</param>
        /// <returns>true:为不存在</returns>
        public bool HasInstance(Expression<Func<T, bool>> where)
        {
            if (_DbSet.Where(where).FirstOrDefault() == null)
                return true;
            else
                return false;
        }

        public bool HasRelevanceInstance<T2>(Expression<Func<T2, bool>> where)
        {
            var dbSet = _Context.Set(typeof(T2)) as IQueryable<T2>; ;
            if (dbSet.Where(where).FirstOrDefault() != null)
                return true;
            else
                return false;
        }
        public T GetByStringID(string oid)
        {
            return _DbSet.Find(oid);
        }

        public T GetByGuid(Guid oid)
        {
            return _DbSet.Find(oid);
        }

        /// <summary>
        /// 根据Lambda表达式获取一条数据
        /// </summary>
        /// <param name="where"></param>
        /// <returns></returns>
        public T GetByLambda(Expression<Func<T, bool>> where)
        {
            try
            {
                return _DbSet.Where(where).FirstOrDefault<T>();
            }
            catch (Exception e)
            {
                return null;
            }
        }


        //根据Guid获取一条数据,如果该数据不存在将创建一条数据,然后返回
        public T GetOrCreatePersistence(Guid id)
        {
            var fObject = this.GetByGuid(id);
            if (fObject != null)
                return fObject;
            else
            {
                fObject = Activator.CreateInstance<T>();
                this.Add(fObject);
                return fObject;
            }
        }

        public T GetOrCreateNotPersistence(Guid id)
        {
            var fObject = this.GetByGuid(id);
            if (fObject != null)
                return fObject;
            else
            {
                fObject = Activator.CreateInstance<T>();
                return fObject;
            }
        }

        public void Add(T bo)
        {
            _DbSet.Add(bo);
            _Context.SaveChanges();
        }
        public void DelayedAdd(T bo)
        {
            _DbSet.Add(bo);
        }
        public int AllSaveChanges()
        {
            return _Context.SaveChanges();

        }
        public void AddOrUpdate(T bo, bool isForNewObject, ref int returnPoint)
        {
            if (isForNewObject)
            {
                this.Add(bo);
                returnPoint = 1;
            }
            else
            {
                this.Update(bo);
            }
        }
        /// <summary>
        /// 物理删除
        /// </summary>
        /// <param name="bo"></param>
        public void DeleteEntity(T bo)
        {
            _DbSet.Remove(bo);
            _Context.SaveChanges();
        }
        /// <summary>
        /// 物理删除
        /// </summary>
        /// <param name="bo"></param>
        public void DeleteByIds(params object[] ids)
        {
            if (ids != null)
            {
                string strIds = string.Join(",", ids);
                _Context.Database.ExecuteSqlCommand(string.Format("delete {0}  where  ID  in ('{1}')  ", typeof(T).Name, strIds));
            }
        }
        /// <summary>
        /// 逻辑删除(使用时确保表中 含有用于标记逻辑删除的字段 IsDelete)
        /// </summary>
        /// <param name="bo"></param>
        public void Delete(T bo)
        {
            PropertyInfo[] properties = typeof(T).GetProperties();
            for (int i = properties.Length; i > 0; i--)
            {
                string fn = properties[i - 1].Name;
                PropertyInfo pinfo = typeof(T).GetProperty(fn);
                if ("IsDelete" == fn)
                {
                    pinfo.SetValue(bo, true, null);
                    break;
                }
            }
            _DbSet.Attach(bo);
            _Context.Entry(bo).State = EntityState.Modified;
            _Context.SaveChanges();
        }
        public void DeleteRelevenceObject<T2>(T2 relevanceBo)
        {
            var dbSet = _Context.Set(typeof(T2));
            dbSet.Remove(relevanceBo);
            _Context.SaveChanges();
        }

        public void DeleteRelevenceObjectsByLambda<T2>(Expression<Func<T2, bool>> where)
        {
            var dbSet = _Context.Set(typeof(T2));

            var tempCollection = dbSet as IQueryable<T2>;
            foreach (var item in tempCollection.Where(where))
                dbSet.Remove(item);

            _Context.SaveChanges();
        }

        public void Update(T bo)
        {
            _DbSet.Attach(bo);
            _Context.Entry(bo).State = EntityState.Modified;
            _Context.SaveChanges();
        }

        public IQueryable<T> GetAll()
        {
            return _DbSet as IQueryable<T>;
        }

        //获取所有数据,根据条件排序
        public IQueryable<T> GetAllOrdered(Expression<Func<T, bool>> order)
        {
            return _DbSet.OrderBy(order);
        }

        public IQueryable<T> GetMany(Expression<Func<T, bool>> where)
        {
            return _DbSet.Where(where) as IQueryable<T>;
        }

        public IQueryable<T> GetMany(Expression<Func<T, object>> selector, object val)
        {
            //var queryBuilder = CustomLinq.Func((selector, val) =>
            //      from c in _DbSet.ToExpandable()
            //      where selector.Expand(c).IndexOf(val) != -1
            //      select c);
            return _DbSet as IQueryable<T>;
        }

        public IQueryable<T> GetManyOrdered<TKey>(Expression<Func<T, bool>> where, Expression<Func<T, TKey>> order)
        {
            return _DbSet.Where(where).OrderBy(order);
        }

        /// <summary>
        /// 分页获取数据
        /// </summary>
        /// <typeparam name="TKey"></typeparam>
        /// <param name="dataTableModel">表格参数</param>
        /// <param name="dataAmount">总条数</param>
        /// <param name="orderProperty">要排序的对象名称</param>
        /// <param name="where">搜索条件</param>
        /// <returns></returns>
        //public IQueryable<T> GetDataPaging(DataTableModel dataTableModel, ref int dataAmount, string orderProperty, Expression<Func<T, bool>> where = null)
        //{
        //    var searchResult = _DbSet as IQueryable<T>;
        //    if (where != null)
        //        searchResult = searchResult.Where(where);

        //    dataAmount = searchResult.Count();
        //    var isDesc = dataTableModel.OrderDir == "desc";
        //    searchResult = searchResult.OrderBy(orderProperty, isDesc).Skip(dataTableModel.Start).Take(dataTableModel.Length);
        //    return searchResult;
        //}

        public IQueryable<T> GetAllOrderedPaged<TKey>(Expression<Func<T, TKey>> order, int page, int pageSize, ref int pageAmount, ref int boAmount, ref bool isDesc)
        {
            var searchResult = _DbSet as IQueryable<T>;
            boAmount = searchResult.Count();
            pageAmount = boAmount / pageSize;
            if (boAmount > pageAmount * pageSize)
                pageAmount = pageAmount + 1;
            return searchResult.OrderBy(order).Skip((page - 1) * pageSize).Take(pageSize);
        }
        public IQueryable<T> GetAllCommonWay(
            ref int pageAmount,
            ref int boAmount,
            Expression<Func<T, bool>> where = null,
            Expression<Func<T, bool>> order = null,
            bool? isDesc = null,
            int? page = null,
            int? pageSize = null)
        {
            pageAmount = 0;
            boAmount = 0;
            var searchResult = _DbSet as IQueryable<T>;


            if (where != null && order != null)
            {
                searchResult = searchResult.Where(where);
                if (isDesc != null)
                    searchResult = searchResult.OrderByDescending(order);
                else
                    searchResult = searchResult.OrderBy(order);
            }
            else
            {
                if (where != null)
                {
                    searchResult = searchResult.Where(where);
                }
                else
                {
                    if (order != null)
                    {
                        if (isDesc != null)
                            searchResult = searchResult.OrderByDescending(order);
                        else
                            searchResult = searchResult.OrderBy(order);
                    }
                }
            }

            boAmount = searchResult.Count();
            if (pageAmount == -1)
            {
                pageAmount = -1;
            }

            if (page != null)
            {
                var p = (int)page;
                var ps = (int)pageSize;
                pageAmount = searchResult.Count() / ps;
                searchResult = searchResult.Skip((p - 1) * ps).Take(ps);
            }

            return searchResult;
        }

        public bool CanAdd(Expression<Func<T, bool>> where)
        {
            var count = _DbSet.Where(where).Count();
            if (count > 0)
                return false;
            else
                return true;
        }

        public T2 GetRelevanceObject<T2>(Guid id)
        {
            var dbSet = _Context.Set(typeof(T2));
            return (T2)dbSet.Find(id);
        }

        public T2 GetRelevanceObjectBySqlQuery<T2>(string SqlQureyString)
        {
            var id = _Context.Database.SqlQuery<Guid>(SqlQureyString).FirstOrDefault();
            if (id != null)
            {
                return GetRelevanceObject<T2>(id);
            }
            else
                return default(T2);
        }

        public T2 GetRelevanceObject<T2>(Expression<Func<T2, bool>> where)
        {
            var dbSet = _Context.Set(typeof(T2)) as IQueryable<T2>;
            return (T2)dbSet.Where(where).FirstOrDefault();
        }

        public IQueryable<T2> GetRelevanceObjects<T2>(Expression<Func<T2, bool>> where)
        {
            var dbSet = _Context.Set(typeof(T2));
            var searchResult = dbSet as IQueryable<T2>;

            return searchResult.Where(where);
        }

        public IQueryable<T2> GetRelevanceObjects<T2>(
            Expression<Func<T2, bool>> where = null,
            Expression<Func<T2, bool>> order = null,
            bool? isDesc = null)
        {
            var dbSet = _Context.Set(typeof(T2));
            var searchResult = dbSet as IQueryable<T2>;
            if (where != null && order != null)
            {
                searchResult = searchResult.Where(where);
                if (isDesc != null)
                    searchResult = searchResult.OrderByDescending(order);
                else
                    searchResult = searchResult.OrderBy(order);
            }
            else
            {
                if (where != null)
                {
                    searchResult = searchResult.Where(where);
                }
                else
                {
                    if (order != null)
                    {
                        if (isDesc != null)
                            searchResult = searchResult.OrderByDescending(order);
                        else
                            searchResult = searchResult.OrderBy(order);
                    }
                }
            }

            return searchResult;
        }


        public void AddRelevanceObject<T2>(T2 relevanceBo)
        {
            var dbSet = _Context.Set(typeof(T2));
            dbSet.Add(relevanceBo);
            _Context.SaveChanges();
        }

        public void UpdateRelevanceObject<T2>(T2 relevanceBo)
        {
            var tempBo = Activator.CreateInstance(typeof(T2));
            tempBo = relevanceBo;
            var dbSet = _Context.Set(typeof(T2));
            dbSet.Attach(tempBo);
            _Context.Entry(tempBo).State = EntityState.Modified;
            _Context.SaveChanges();
        }


        ///// <summary>
        ///// 从缓存中获取所有数据
        ///// </summary>
        ///// <returns></returns>
        //public ICollection<T> GetAllByCache()
        //{
        //    var key = typeof(T).Name + "List";
        //    var obj = this.GetByCache(key);
        //    if (obj == null)
        //    {
        //        obj = this.GetAll().ToList();
        //        this.SetInCache(key, obj);
        //    }
        //    return obj as ICollection<T>;
        //}
        ///// <summary>
        ///// 从缓存中获取单个实体
        ///// </summary>
        ///// <param name="id"></param>
        ///// <returns></returns>
        //public T GetByCache(Guid id)
        //{
        //    var key = id.ToString();
        //    var obj = this.GetByCache(key);
        //    if (obj == null)
        //    {
        //        obj = this.GetByGuid(id);
        //        this.SetInCache(key, obj);
        //    }
        //    return obj as T;
        //}

        ///// <summary>
        ///// 移除缓存中的数据(集合)
        ///// </summary>
        //public void RemoveAllCache()
        //{
        //    var key = typeof(T).Name + "List";
        //    this.RemoveCache(key);
        //}
        ///// <summary>
        ///// 移除缓存中的数据(单个实体)
        ///// </summary>
        ///// <param name="id"></param>
        //public void RemoveCache(Guid id)
        //{
        //    var key = id.ToString();
        //    this.RemoveCache(key);
        //}
        /// <summary>
        /// 设置缓存
        /// </summary>
        /// <param name="key"></param>
        /// <param name="val"></param>
        //public void SetInCache(string key, object val)
        //{
        //    CacheHelper.Set(key, val);
        //}
        ///// <summary>
        ///// 从缓存中获取数据
        ///// </summary>
        ///// <param name="key"></param>
        ///// <returns></returns>
        //public object GetByCache(string key)
        //{
        //    return CacheHelper.Get(key);
        //}
        ///// <summary>
        ///// 从缓存中移除数据
        ///// </summary>
        ///// <param name="key"></param>
        //public void RemoveCache(string key)
        //{
        //    CacheHelper.Remove(key);
        //}
    }
/// <summary>
    /// 基于 EF CodeFirst 独立的针对 IBaseEntityService 方法的实现,其实际实现时通过继承的方式处理
    /// </summary>
    public abstract class BaseEntityService<T> where T : class
    {
        private  readonly DbContext _Context;
        private  readonly IDbSet<T> _DbSet;

        public BaseEntityService(DbContext context)
        {
            this._Context = context;
            _DbSet = _Context.Set<T>();
        }
        /// <summary>
        /// 根据条件判断是否数据存在
        /// </summary>
        /// <param name="where">判断条件</param>
        /// <returns></returns>
        public  bool HasInstance(Expression<Func<T, bool>> where)
        {
            if (_DbSet.Where(where).FirstOrDefault() != null)
                return true;
            else
                return false;
        }
        /// <summary>
        /// 根据条件判断是否数据存在
        /// </summary>
        /// <typeparam name="T2">需要判断实体</typeparam>
        /// <param name="where">判断条件</param>
        /// <returns></returns>
        public bool HasRelevanceInstance<T2>(Expression<Func<T2, bool>> where)
        {
            var dbSet = _Context.Set(typeof(T2)) as IQueryable<T2>; ;
            if (dbSet.Where(where).FirstOrDefault() != null)
                return true;
            else
                return false;
        }
        /// <summary>
        /// 根据主键ID获取实体
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public T GetByIntID(int id)
        {
            return _DbSet.Find(id);
        }
        /// <summary>
        /// 根据主键ID获取实体
        /// </summary>
        /// <param name="oid"></param>
        /// <returns></returns>
        public T GetByStringID(string oid)
        {
            return _DbSet.Find(oid);
        }
        /// <summary>
        /// 根据主键ID获取实体
        /// </summary>
        /// <param name="oid"></param>
        /// <returns></returns>
        public T GetByGuid(Guid oid)
        {
            return _DbSet.Find(oid);
        }
        /// <summary>
        /// 根据条件获取实体
        /// </summary>
        /// <param name="where">刷选条件</param>
        /// <returns></returns>
        public T GetByLambda(Expression<Func<T, bool>> where)
        {

            return _DbSet.Where(where).FirstOrDefault<T>();
        }

        public T GetOrCreatePersistence(Guid id)
        {
            var fObject = this.GetByGuid(id);
            if (fObject != null)
                return fObject;
            else
            {
                fObject = Activator.CreateInstance<T>();
                this.Add(fObject);
                return fObject;
            }
        }

        public T GetOrCreateNotPersistence(Guid id)
        {
            var fObject = this.GetByGuid(id);
            if (fObject != null)
                return fObject;
            else
            {
                fObject = Activator.CreateInstance<T>();
                return fObject;
            }
        }
       /// <summary>
       /// 添加数据
       /// </summary>
       /// <param name="bo">实体</param>
        public void Add(T bo)
        {
                _DbSet.Add(bo);
                _Context.SaveChanges();
        }
        /// <summary>
        /// 添加或者更新数据
        /// </summary>
        /// <param name="bo">实体</param>
        /// <param name="isForNewObject">是否新增</param>
        /// <param name="updatedProperties">过滤字段</param>
        public void AddOrUpdate(T bo, bool isForNewObject=true, params Expression<Func<T, object>>[] updatedProperties)
        {
            if (isForNewObject)
            {
                this.Add(bo);
            }
            else
            {
                this.Update(bo,updatedProperties);
            }
        }
        /// <summary>
        /// 删除数据
        /// </summary>
        /// <param name="bo">实体</param>
        public void Delete(T bo)
        {
            _DbSet.Remove(bo);
            _Context.SaveChanges();
        }

        /// <summary>
        /// 根据stringID删除数据
        /// </summary>
        /// <param name="id"></param>
        public void Delete(string id)
        {
            _DbSet.Remove(GetByStringID(id));
            _Context.SaveChanges();
        }
        /// <summary>
        /// 根据主键ID删除数据(int)
        /// </summary>
        /// <param name="id"></param>
        public void Delete(int id)
        {
            _DbSet.Remove(GetByIntID(id));
            _Context.SaveChanges();
        }

        //public void DeleteByLambda(Expression<Func<T, bool>> where)
        //{
        //    _DbSet.Delete(where);
        //    _Context.SaveChanges();
        //}
        /// <summary>
        /// 删除数据
        /// </summary>
        /// <typeparam name="T2"></typeparam>
        /// <param name="relevanceBo"></param>
        public void DeleteRelevenceObject<T2>(T2 relevanceBo)
        {
            var dbSet = _Context.Set(typeof(T2));
            dbSet.Remove(relevanceBo);
            _Context.SaveChanges();
        }
        /// <summary>
        /// 根据刷选添加循环删除
        /// </summary>
        /// <typeparam name="T2">需要删除的实体</typeparam>
        /// <param name="where">删除条件</param>
        public void DeleteRelevenceObjectsByLambda<T2>(Expression<Func<T2, bool>> where)
        {
            var dbSet = _Context.Set(typeof(T2));

            var tempCollection = dbSet as IQueryable<T2>;
            foreach (var item in tempCollection.Where(where))
                dbSet.Remove(item);

            _Context.SaveChanges();
        }
        /// <summary>
        /// 更新实体
        /// </summary>
        /// <param name="bo">实体</param>
        public void Update(T bo)
        {
            _DbSet.Attach(bo);
            _Context.Entry(bo).State = EntityState.Modified;
            _Context.SaveChanges();
        }
        /// <summary>
        /// 更新实体,并过滤不需要更新列
        /// </summary>
        /// <param name="entity">实体</param>
        /// <param name="updatedProperties">过滤不需要更实体数组</param>
        public void Update(T entity, params Expression<Func<T, object>>[] updatedProperties)
        {
            _DbSet.Attach(entity);
            var dbEntityEntry = _Context.Entry(entity);
            _Context.Entry(entity).State = EntityState.Modified;
            if (updatedProperties.Any())
            {
                foreach (var property in updatedProperties)
                {
                    dbEntityEntry.Property(property).IsModified = false;
                }
            }
         
            _Context.SaveChanges();

        }
            /// <summary>
            /// 获取实体所有信息
            /// </summary>
            /// <returns></returns>
            public IQueryable<T> GetAll()
        {
            return _DbSet as IQueryable<T>;
        }
        /// <summary>
        /// 获取实体信息并排序
        /// </summary>
        /// <param name="order"></param>
        /// <returns></returns>
        public IQueryable<T> GetAllOrdered(Expression<Func<T, bool>> order)
        {
            return _DbSet.OrderBy(order);
        }
        /// <summary>
        /// 筛选获取实体
        /// </summary>
        /// <param name="where"></param>
        /// <returns></returns>
        public IQueryable<T> GetMany(Expression<Func<T, bool>> where)
        {
            return _DbSet.Where(where) as IQueryable<T>;
        }

        public IQueryable<T> GetMany(Expression<Func<T, object>> selector, object val)
        {
            //var queryBuilder = CustomLinq.Func((selector, val) =>
            //      from c in _DbSet.ToExpandable()
            //      where selector.Expand(c).IndexOf(val) != -1
            //      select c);
            return _DbSet as IQueryable<T>;
        }

        public IQueryable<T> GetManyOrdered<TKey>(Expression<Func<T, bool>> where, Expression<Func<T, TKey>> order)
        {
            return _DbSet.Where(where).OrderBy(order);
        }

        public IQueryable<T> GetAllOrderedPaged(string orderProeprtyName, int page, int pageSize, ref int pageAmount, ref int boAmount, ref bool isDesc)
        {
            var searchResult = _DbSet as IQueryable<T>;
            boAmount = searchResult.Count();
            pageAmount = boAmount / pageSize;
            return searchResult;
        }

        public IQueryable<T> GetAllOrderedPaged<TKey>(Expression<Func<T, TKey>> order, int page, int pageSize, ref int pageAmount, ref int boAmount, ref bool isDesc)
        {
            var searchResult = _DbSet as IQueryable<T>;
            boAmount = searchResult.Count();
            pageAmount = boAmount / pageSize;
            if (boAmount > pageAmount * pageSize)
                pageAmount = pageAmount + 1;
            return searchResult.OrderBy(order).Skip((page - 1) * pageSize).Take(pageSize);
        }

        public IQueryable<T> GetManyOrderedPaged<Tkey>(Expression<Func<T, bool>> where, Expression<Func<T, Tkey>> order, int page, int pageSize, ref int pageAmount, ref int boAmount, ref bool isDesc)
        {
            var searchResult = _DbSet.Where(where) as IQueryable<T>;
            boAmount = searchResult.Count();
            pageAmount = boAmount / pageSize;
            if (boAmount > pageAmount * pageSize)
                pageAmount = pageAmount + 1;

            if (!isDesc)
                return searchResult.OrderBy(order).Skip((page - 1) * pageSize).Take(pageSize);
            else
                return searchResult.OrderByDescending(order).Skip((page - 1) * pageSize).Take(pageSize);
        }

        ///// <summary>
        ///// 分页获取数据
        ///// </summary>
        ///// <param name="page">分页基础类</param>
        ///// <param name="dataAmount">输出总数量</param>
        ///// <param name="where">筛选条件</param>
        ///// <returns></returns>
        //public IQueryable<T> GetDataPaging(GridPager page, ref int dataAmount, Expression<Func<T, bool>> where = null)
        //{
        //    var searchResult = _DbSet as IQueryable<T>;
        //    if (where != null)
        //        searchResult = searchResult.Where(where);
        //    dataAmount = searchResult.Count();
        //    var isDesc = page.order == "desc";
        //    searchResult = searchResult.OrderBy(page.sort, isDesc).Skip(page.thisCount).Take(page.rows);
        //    return searchResult;
        //}

        public IQueryable<T> GetManyOrderedByProertyNamePaged(
            Expression<Func<T, bool>> where,
            string orderProeprtyName,
            int page,
            int pageSize,
            ref int pageAmount,
            ref int boAmount,
            ref bool isDesc
            )
        {
            if (where != null)
            {
                var searchResult = _DbSet.Where(where) as IQueryable<T>;
                boAmount = searchResult.Count();
                pageAmount = boAmount / pageSize;
                if (boAmount > pageAmount * pageSize)
                    pageAmount = pageAmount + 1;

                return searchResult;
            }
            else
            {
                var searchResult = _DbSet as IQueryable<T>;
                boAmount = searchResult.Count();
                pageAmount = boAmount / pageSize;
                if (boAmount > pageAmount * pageSize)
                    pageAmount = pageAmount + 1;

                return searchResult;
            }

        }


        public IQueryable<T> GetAllCommonWay(
            ref int pageAmount,
            ref int boAmount,
            Expression<Func<T, bool>> where = null,
            Expression<Func<T, bool>> order = null,
            bool? isDesc = null,
            int? page = null,
            int? pageSize = null)
        {
            pageAmount = 0;
            boAmount = 0;
            var searchResult = _DbSet as IQueryable<T>;


            if (where != null && order != null)
            {
                searchResult = searchResult.Where(where);
                if (isDesc != null)
                    searchResult = searchResult.OrderByDescending(order);
                else
                    searchResult = searchResult.OrderBy(order);
            }
            else
            {
                if (where != null)
                {
                    searchResult = searchResult.Where(where);
                }
                else
                {
                    if (order != null)
                    {
                        if (isDesc != null)
                            searchResult = searchResult.OrderByDescending(order);
                        else
                            searchResult = searchResult.OrderBy(order);
                    }
                }
            }

            boAmount = searchResult.Count();
            if (pageAmount == -1)
            {
                pageAmount = -1;
            }

            if (page != null)
            {
                var p = (int)page;
                var ps = (int)pageSize;
                pageAmount = searchResult.Count() / ps;
                searchResult = searchResult.Skip((p - 1) * ps).Take(ps);
            }

            return searchResult;
        }

        public bool CanAdd(Expression<Func<T, bool>> where)
        {
            var count = _DbSet.Where(where).Count();
            if (count > 0)
                return false;
            else
                return true;
        }

        public T2 GetRelevanceObject<T2>(Guid id)
        {
            var dbSet = _Context.Set(typeof(T2));
            return (T2)dbSet.Find(id);
        }

        public T2 GetRelevanceObjectBySqlQuery<T2>(string SqlQureyString)
        {
            var id = _Context.Database.SqlQuery<Guid>(SqlQureyString).FirstOrDefault();
            if (id != null)
            {
                return GetRelevanceObject<T2>(id);
            }
            else
                return default(T2);
        }

        public T2 GetRelevanceObject<T2>(Expression<Func<T2, bool>> where)
        {
            var dbSet = _Context.Set(typeof(T2)) as IQueryable<T2>;
            return (T2)dbSet.Where(where).FirstOrDefault();
        }

        public IQueryable<T2> GetRelevanceObjects<T2>(Expression<Func<T2, bool>> where)
        {
            var dbSet = _Context.Set(typeof(T2));
            var searchResult = dbSet as IQueryable<T2>;

            return searchResult.Where(where);
        }

        public IQueryable<T2> GetRelevanceObjects<T2>(
            Expression<Func<T2, bool>> where = null,
            Expression<Func<T2, bool>> order = null,
            bool? isDesc = null)
        {
            var dbSet = _Context.Set(typeof(T2));
            var searchResult = dbSet as IQueryable<T2>;
            if (where != null && order != null)
            {
                searchResult = searchResult.Where(where);
                if (isDesc != null)
                    searchResult = searchResult.OrderByDescending(order);
                else
                    searchResult = searchResult.OrderBy(order);
            }
            else
            {
                if (where != null)
                {
                    searchResult = searchResult.Where(where);
                }
                else
                {
                    if (order != null)
                    {
                        if (isDesc != null)
                            searchResult = searchResult.OrderByDescending(order);
                        else
                            searchResult = searchResult.OrderBy(order);
                    }
                }
            }

            return searchResult;
        }

        public IQueryable<T2> GetManyRelevanceObjectsOrderedByProertyNamePaged<T2>(
            Expression<Func<T2, bool>> where,
            string orderProeprtyName,
            int page,
            int pageSize,
            ref int pageAmount,
            ref int boAmount,
            ref bool isDesc)
        {
            var dbSet = _Context.Set(typeof(T2));

            if (where != null)
            {
                var searchResult = (dbSet as IQueryable<T2>).Where(where) as IQueryable<T2>;
                boAmount = searchResult.Count();
                pageAmount = boAmount / pageSize;
                if (boAmount > pageAmount * pageSize)
                    pageAmount = pageAmount + 1;

                return searchResult;
            }
            else
            {
                var searchResult = dbSet as IQueryable<T2>;
                boAmount = searchResult.Count();
                pageAmount = boAmount / pageSize;
                if (boAmount > pageAmount * pageSize)
                    pageAmount = pageAmount + 1;

                return searchResult;
            }

        }

        public void AddRelevanceObject<T2>(T2 relevanceBo)
        {
            var dbSet = _Context.Set(typeof(T2));
            dbSet.Add(relevanceBo);
            _Context.SaveChanges();
        }

        public void UpdateRelevanceObject<T2>(T2 relevanceBo)
        {
            var tempBo = Activator.CreateInstance(typeof(T2));
            tempBo = relevanceBo;
            var dbSet = _Context.Set(typeof(T2));
            dbSet.Attach(tempBo);
            _Context.Entry(tempBo).State = EntityState.Modified;
            _Context.SaveChanges();
        }



    }

通过以上步骤,一个基本简单的仓储完成了。

接下来一般的话,是使用三层Model,DAL,BLL,由于我个人比较懒,直接跳过了DAL层,在BLL层进行业务处理。

新建一个ArticleBLL,对业务的操作。

public class ArticleBLL : BaseEntityService<ZWStar_Article>, IBaseEntityService<ZWStar_Article>
    {
        public ArticleBLL() : base(EFDbContext.GetDbContext()) { }
    }

 

 

 此刻,基本的仓储完成,下篇将介绍如果结合layui完成菜单的添加

原文出处:https://www.cnblogs.com/chenyongsheng/p/12515765.html

展开阅读全文
打赏
0
0 收藏
分享
加载中
更多评论
打赏
0 评论
0 收藏
0
分享
返回顶部
顶部