MVC Repository 模式

public interface IRepository<TEntity> where TEntity : class
    {

        IQueryable<TEntity> Get(
            Expression<Func<TEntity, bool>> filter = null,
            Func<IQueryable<TEntity>, IOrderedQueryable<TEntity>> orderBy = null,
            string includeProperties = "");

        /// <summary>
        /// 获取一个实体对象
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        TEntity GetByID(object id);

        /// <summary>
        /// 添加一个实体对象
        /// </summary>
        /// <param name="entity"></param>
        void Insert(TEntity entity);

        /// <summary>
        /// 根据编号删除一个实体对象
        /// </summary>
        /// <param name="id"></param>
        void Delete(object id);

        /// <summary>
        /// 直接删除一个实体对象
        /// </summary>
        /// <param name="entityToDelete"></param>
        void Delete(TEntity entityToDelete);

        /// <summary>
        /// 更新一个实体对象
        /// </summary>
        /// <param name="entityToUpdate"></param>
        void Update(TEntity entityToUpdate);

        /// <summary>
        /// 使用原始sql获取对象
        /// </summary>
        /// <param name="query"></param>
        /// <param name="parameters"></param>
        /// <returns></returns>
        IQueryable<TEntity> GetWithRawSql(string query, params object[] parameters);

        /// <summary>
        /// 获取对象的可查询表格
        /// </summary>
        IQueryable<TEntity> Table { get; }

        /// <summary>
        /// 使用原始sql删除对象
        /// </summary>
        /// <param name="query"></param>
        /// <param name="parameters"></param>
        void DeleteRawSql(string query, params object[] parameters);

        /// <summary>
        /// 使用原始sql更新对象对象
        /// </summary>
        /// <param name="query"></param>
        /// <param name="parameters"></param>
        void UpdateRawSql(string query, params object[] parameters);


        /// <summary>
        /// 延迟添加,不提交
        /// </summary>
        /// <param name="entity"></param>
        void DelayAdd(TEntity entity);


        /// <summary>
        /// 延迟修改,不提交
        /// </summary>
        /// <param name="entity"></param>
        void DelayUpdate(TEntity entity);

        /// <summary>
        /// 延迟删除,不提交
        /// </summary>
        /// <param name="entity"></param>
        void DelayDelete(TEntity entity);

        /// <summary>
        /// 把延迟操作全部提交
        /// </summary>
        void DelaySubmit();

        /// <summary>
        /// 执行proc_daily存储过程
        /// </summary>
        /// <returns></returns>
        int ProcDaily(ObjectParameter para);

        /// <summary>
        /// 执行proc_update_closingrate_maturityDate存储过程
        /// </summary>
        /// <returns></returns>
        int ProcUpdateClosingrateMaturityDate();

        /// <summary>
        /// 调用存储过程,SQLProcedureResult 返回各种结果
        /// </summary>
        /// <param name="procName"></param>
        /// <param name="parameters"></param>
        /// <returns></returns>
        SQLProcedureHelp.SQLProcedureResult ExeProcedure(string procName, params object[] parameters);
    }
IRepository
public class Repository<TEntity> : IRepository<TEntity> where TEntity : class
    {
        internal OptionTradeDBEntities _context;
        internal DbSet<TEntity> _dbSet;

        public Repository()
        {
            this._context = new OptionTradeDBEntities();
            this._dbSet = this._context.Set<TEntity>();
        }



        public Repository(OptionTradeDBEntities context)
        {
            this._context = context;
            this._dbSet = _context.Set<TEntity>();
        }



        public virtual IQueryable<TEntity> Get(
            Expression<Func<TEntity, bool>> filter = null,
            Func<IQueryable<TEntity>, IOrderedQueryable<TEntity>> orderBy = null,
            string includeProperties = "")
        {
            IQueryable<TEntity> query = _dbSet;

            if (filter != null)
            {
                query = query.Where(filter);
            }

            foreach (var includeProperty in includeProperties.Split
                (new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries))
            {
                query = query.Include(includeProperty);
            }

            if (orderBy != null)
            {
                return orderBy(query);
            }
            else
            {
                return query;
            }
        }

        public virtual TEntity GetByID(object id)
        {
            return _dbSet.Find(id);
        }

        public virtual void Insert(TEntity entity)
        {
            _dbSet.Add(entity);
            try
            {
                _context.SaveChanges();
            }
            catch (DbEntityValidationException e)
            {
                foreach (var eve in e.EntityValidationErrors)
                {
                    Console.WriteLine("Entity of type \"{0}\" in state \"{1}\" has the following validation errors:",
                        eve.Entry.Entity.GetType().Name, eve.Entry.State);
                    foreach (var ve in eve.ValidationErrors)
                    {
                        Console.WriteLine("- Property: \"{0}\", Error: \"{1}\"",
                            ve.PropertyName, ve.ErrorMessage);
                    }
                }
                throw;
            }
        }

        public virtual void Delete(object id)
        {
            TEntity entityToDelete = _dbSet.Find(id);
            if (entityToDelete != null)
                Delete(entityToDelete);
        }

        public virtual void Delete(TEntity entityToDelete)
        {
            if (_context.Entry(entityToDelete).State == EntityState.Detached)
            {
                _dbSet.Attach(entityToDelete);
            }
            _dbSet.Remove(entityToDelete);
            _context.SaveChanges();
        }

        public virtual void Update(TEntity entityToUpdate)
        {
            //_dbSet.Attach(entityToUpdate);
            _context.Entry(entityToUpdate).State = EntityState.Modified;

            try
            {
                _context.SaveChanges();
            }
            catch (DbEntityValidationException e)
            {
                foreach (var eve in e.EntityValidationErrors)
                {
                    Console.WriteLine("Entity of type \"{0}\" in state \"{1}\" has the following validation errors:",
                        eve.Entry.Entity.GetType().Name, eve.Entry.State);
                    foreach (var ve in eve.ValidationErrors)
                    {
                        Console.WriteLine("- Property: \"{0}\", Error: \"{1}\"",
                            ve.PropertyName, ve.ErrorMessage);
                    }
                }
                throw;
            }

        }

        public virtual IQueryable<TEntity> GetWithRawSql(string query, params object[] parameters)
        {
            return _dbSet.SqlQuery(query, parameters).ToList().AsQueryable();
        }

        public virtual IQueryable<TEntity> Table
        {
            get
            {
                return this._dbSet;
            }
        }


        public void DeleteRawSql(string query, params object[] parameters)
        {
            _context.Database.ExecuteSqlCommand(query, parameters);
        }


        public void UpdateRawSql(string query, params object[] parameters)
        {
            _context.Database.ExecuteSqlCommand(query, parameters);
        }


        public void DelayAdd(TEntity entity)
        {
            _dbSet.Add(entity);
        }

        public void DelayUpdate(TEntity entity)
        {
            _context.Entry(entity).State = EntityState.Modified;
        }

        public void DelayDelete(TEntity entity)
        {
            if (_context.Entry(entity).State == EntityState.Detached)
            {
                _dbSet.Attach(entity);
            }
            _dbSet.Remove(entity);
        }

        public void DelaySubmit()
        {
            try
            {
                _context.SaveChanges();
            }
            catch (DbEntityValidationException e)
            {
                foreach (var eve in e.EntityValidationErrors)
                {
                    Console.WriteLine("Entity of type \"{0}\" in state \"{1}\" has the following validation errors:",
                        eve.Entry.Entity.GetType().Name, eve.Entry.State);
                    foreach (var ve in eve.ValidationErrors)
                    {
                        Console.WriteLine("- Property: \"{0}\", Error: \"{1}\"",
                            ve.PropertyName, ve.ErrorMessage);
                    }
                }
                throw;
            }
        }




        public int ProcDaily(ObjectParameter para)
        {
            return _context.proc_daily(para);
        }


        public int ProcUpdateClosingrateMaturityDate()
        {
            return _context.proc_update_closingrate_maturityDate();

        }


        public SQLProcedureHelp.SQLProcedureResult ExeProcedure(string procName, params object[] parameters)
        {
            SqlConnection sqlConn = (SqlConnection)_context.Database.Connection;

            try
            {
                SQLProcedureHelp.SQLProcedure sqlProcedure = new SQLProcedureHelp.SQLProcedure(sqlConn);
                SQLProcedureHelp.SQLProcedureResult result = sqlProcedure.Call(procName, parameters);
                return result;
            }
            catch
            {
                throw;
            }
            finally
            {
                sqlConn.Close();
            }
        }
    }
Repository
public interface IService<TEntity> where TEntity : class
    {
        IEnumerable<TEntity> Get(
            Expression<Func<TEntity, bool>> filter = null,
            Func<IQueryable<TEntity>, IOrderedQueryable<TEntity>> orderBy = null,
            string includeProperties = "");

        /// <summary>
        /// 获取一个实体对象
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        TEntity GetByID(object id);

        /// <summary>
        /// 添加一个实体对象
        /// </summary>
        /// <param name="entity"></param>
        void Insert(TEntity entity);

        /// <summary>
        /// 根据编号删除一个实体对象
        /// </summary>
        /// <param name="id"></param>
        void Delete(object id);

        /// <summary>
        /// 直接删除一个实体对象
        /// </summary>
        /// <param name="entityToDelete"></param>
        void Delete(TEntity entityToDelete);

        /// <summary>
        /// 更新一个实体对象
        /// </summary>
        /// <param name="entityToUpdate"></param>
        void Update(TEntity entityToUpdate);

        /// <summary>
        /// 使用原始sql获取对象
        /// </summary>
        /// <param name="query"></param>
        /// <param name="parameters"></param>
        /// <returns></returns>
        IEnumerable<TEntity> GetWithRawSql(string query, params object[] parameters);

        /// <summary>
        /// 获取对象的可查询表格
        /// </summary>
        IQueryable<TEntity> Table();


        /// <summary>
        /// 使用原始sql删除对象
        /// </summary>
        /// <param name="query"></param>
        /// <param name="parameters"></param>
        void DeleteRawSql(string query, params object[] parameters);

        /// <summary>
        /// 延迟添加,不提交
        /// </summary>
        /// <param name="entity"></param>
        void DelayAdd(TEntity entity);

        /// <summary>
        /// 延迟更新,不提交
        /// </summary>
        /// <param name="entity"></param>
        void DelayUpdate(TEntity entity);

        /// <summary>
        /// 延迟删除,不提交
        /// </summary>
        /// <param name="entity"></param>
        void DelayDelete(TEntity entity);

        /// <summary>
        /// 把延迟操作全部提交
        /// </summary>
        void DelaySubmit();

        /// <summary>
        /// 执行proc_daily存储过程
        /// </summary>
        /// <returns></returns>
        int ProcDaily(ObjectParameter para);

        /// <summary>
        /// 执行proc_update_closingrate_maturityDate存储过程
        /// </summary>
        /// <returns></returns>
        int ProcUpdateClosingrateMaturityDate();

        /// <summary>
        /// 调用存储过程,SQLProcedureResult 返回各种结果
        /// </summary>
        /// <param name="procName"></param>
        /// <param name="parameters"></param>
        /// <returns></returns>
        SQLProcedureHelp.SQLProcedureResult ExeProcedure(string procName, params object[] parameters);
    }
IService
public class Service<TEntity> : IService<TEntity> where TEntity : class
    {


        IRepository<TEntity> Repo = null;

        public Service()
        {
            this.Repo = new Repository<TEntity>();
        }

        public IEnumerable<TEntity> Get(
             Expression<Func<TEntity, bool>> filter = null,
             Func<IQueryable<TEntity>, IOrderedQueryable<TEntity>> orderBy = null,
             string includeProperties = "")
        {
            return Repo.Get(filter, orderBy, includeProperties);
        }

        public TEntity GetByID(object id)
        {
            return Repo.GetByID(id);
        }

        public void Insert(TEntity entity)
        {
            Repo.Insert(entity);
        }

        public void Delete(object id)
        {
            Repo.Delete(id);
        }

        public void Delete(TEntity entityToDelete)
        {
            Repo.Delete(entityToDelete);
        }

        public void Update(TEntity entityToUpdate)
        {
            Repo.Update(entityToUpdate);
        }

        public IEnumerable<TEntity> GetWithRawSql(string query, params object[] parameters)
        {
            return Repo.GetWithRawSql(query, parameters);
        }

        public IQueryable<TEntity> Table()
        {
            return Repo.Table;
        }


        public void DeleteRawSql(string query, params object[] parameters)
        {
            Repo.DeleteRawSql(query, parameters);
        }


        public void DelayAdd(TEntity entity)
        {
            Repo.DelayAdd(entity);
        }

        public void DelayUpdate(TEntity entity)
        {
            Repo.DelayUpdate(entity);
        }

        public void DelayDelete(TEntity entity)
        {
            Repo.DelayDelete(entity);
        }

        public void DelaySubmit()
        {
            Repo.DelaySubmit();
        }


        public int ProcDaily(ObjectParameter para)
        {
            return Repo.ProcDaily(para);
        }


        public int ProcUpdateClosingrateMaturityDate()
        {
            return Repo.ProcUpdateClosingrateMaturityDate();
        }


        public SQLProcedureHelp.SQLProcedureResult ExeProcedure(string procName, params object[] parameters)
        {
            return Repo.ExeProcedure(procName, parameters);
        }
    }
Service

 

posted @ 2015-12-26 16:15  finly  阅读(177)  评论(0编辑  收藏  举报