面向接口编程框架

面向接口编程框架

框架:MVC+EF模型+面向接口式三层架构+工厂模式,UnitWork模式,使用了t4模板,框架用于分享

github代码下载:https://github.com/zy20081/practice.git

前台代码展示

  public class LoginController : Controller
    {
        public IUserInfoService UserInfoService = new UserInfoService();
        public ActionResult LogOn() 
        {
            return View();
        }
        #region 创建验证码
        public ActionResult GetValidateCode()
        {
            ValidateCode vCode = new ValidateCode();
            string code = vCode.CreateValidateCode(4);//获取随机的数字
            Session["ValidateCode"] = code;////把验证码防到  session
            byte[] bytes = vCode.CreateValidateGraphic(code);
            return File(bytes, @"image/jpeg");
        } 
        #endregion

        #region 用户名/验证码校验
        public ActionResult ProcessUserLogin()
        {
            //校验用户验证码
            //var code = Request["ValidateCode"];
            //if (Session["ValidateCode"] == null || code != Session["ValidateCode"].ToString())
            //{
            //    return Content("验证码错误");
            //}
            //校验用户名密码是否匹配
            string userName = Request["UserName"];
            string userPwd = Request["UserPwd"];
            var currentUser = UserInfoService.LoadEntities(u => u.UserName == userName && u.UPwd == userPwd).FirstOrDefault();
            if (currentUser == null)
            {
                return Content("用户名错误");
            }
            //将用户放到session
            Session["UserInfo"] = currentUser;
            return Content("ok");

        } 
        #endregion
    }

IDAL

IBaseRepository.cs

    public  interface IBaseRepository<T> where T:class,new()
    {
        IQueryable<T> LoadEntities(Func<T, bool> whereLambda);
        IQueryable<T> LoadPageEntities<S>(int pageSize, int pageIndex, out int total, Func<T, bool> whereLambda, Func<T, S> orderByLambda, bool isAsc);
        T AddEntity(T entity);
        bool UpdateEntity(T entity);
        bool DeleteEntity(T entity);
    }

IDbSession.tt

    public partial interface IDbSession
    {
        IActionGroupRepository ActionGroupRepository{get;set;}

        IActionInfoRepository ActionInfoRepository{get;set;}

        IDepartmentRepository DepartmentRepository{get;set;}

        IProductRepository ProductRepository{get;set;}

        IR_UserInfo_AcitonInfoRepository R_UserInfo_AcitonInfoRepository{get;set;}

        IRoleRepository RoleRepository{get;set;}

        IUserInfoRepository UserInfoRepository{get;set;}
    }    

IDbSession.cs

上面和下面是2个部分类,也可以写到一个文件里

 public partial  interface IDbSession
    {
        //IUserInfoRepository UserInfoRepository { get; set; }
        //IProductRepository ProductRepository { get; set; }
        int ExcuteSql(string sql, params ObjectParameter[] Parameters);
        /// <summary>
        /// 将整个数据库访问层的所有的修改都一次性的提交回数据库
        /// 业务逻辑层:一个业务场景,肯定会对多个表做修改,和对多表进行处理,
        /// 有此方法的存在,能极大的提高数据库访问层批量提交sql的性能,提高数据库的吞吐率,减少          了跟数据库的交互次数
        /// </summary>
        int SaveChanges();//UnitWork模式
    }

Reposiotroy.cs

public partial interface IActionGroupRepository :IBaseRepository<ActionGroup>
    {}
    public partial interface IActionInfoRepository :IBaseRepository<ActionInfo>
    {}
    public partial interface IDepartmentRepository :IBaseRepository<Department>
    {}
    public partial interface IProductRepository :IBaseRepository<Product>
    {}
    public partial interface IR_UserInfo_AcitonInfoRepository :IBaseRepository<R_UserInfo_AcitonInfo>
    {}
    public partial interface IRoleRepository :IBaseRepository<Role>
    {}
    public partial interface IUserInfoRepository :IBaseRepository<UserInfo>
    {}

IUserInfoRepository.cs

 public partial interface IUserInfoRepository:IBaseRepository<UserInfo>
    {}

IBLL

IServices.tt 生成类

    public partial interface IActionGroupService : IBaseService<ActionGroup>
    {}   
    public partial interface IActionInfoService : IBaseService<ActionInfo>
    {}   
    public partial interface IDepartmentService : IBaseService<Department>
    {}   
    public partial interface IProductService : IBaseService<Product>
    {}   
    public partial interface IR_UserInfo_AcitonInfoService : IBaseService<R_UserInfo_AcitonInfo>
    {}   
    public partial interface IRoleService : IBaseService<Role>
    {}   
    public partial interface IUserInfoService : IBaseService<UserInfo>
    {}   

IBaseService.cs

 public interface IBaseService<T> where T:class,new () 
    {
        IDbSession DbSession { get; }
        IBaseRepository<T> CurrentReposiotry { get; set; }
        IQueryable<T> LoadEntities(Func<T, bool> whereLambda);
        IQueryable<T> LoadPageEntities<S>(int pageSize, int pageIndex, out int total, Func<T, bool> whereLambda, Func<T, S> orderByLambda, bool isAsc);
        T AddEntity(T entity);
        bool UpdateEntity(T entity);

        bool DeleteEntity(T entity);  
    }

IUserInfoService.cs

    public partial interface IUserInfoService : IBaseService<UserInfo>
    {
       IQueryable<UserInfo> LoadUsers(Model.UserInfoSearchParam param);
       int DeleteUsers(List<int> listIds);
    }

DAL

DbSession.tt 生成类

public partial class DbSession :IDbSession
    {


        private IActionGroupRepository _ActionGroupRepository;
        public IActionGroupRepository ActionGroupRepository
        {
            get
            {
                if(_ActionGroupRepository == null)
                {
                    _ActionGroupRepository = new ActionGroupRepository();
                }
                return _ActionGroupRepository;
            }
            set { _ActionGroupRepository = value; }
        }

        private IActionInfoRepository _ActionInfoRepository;
        public IActionInfoRepository ActionInfoRepository
        {
            get
            {
                if(_ActionInfoRepository == null)
                {
                    _ActionInfoRepository = new ActionInfoRepository();
                }
                return _ActionInfoRepository;
            }
            set { _ActionInfoRepository = value; }
        }

        private IDepartmentRepository _DepartmentRepository;
        public IDepartmentRepository DepartmentRepository
        {
            get
            {
                if(_DepartmentRepository == null)
                {
                    _DepartmentRepository = new DepartmentRepository();
                }
                return _DepartmentRepository;
            }
            set { _DepartmentRepository = value; }
        }

        private IProductRepository _ProductRepository;
        public IProductRepository ProductRepository
        {
            get
            {
                if(_ProductRepository == null)
                {
                    _ProductRepository = new ProductRepository();
                }
                return _ProductRepository;
            }
            set { _ProductRepository = value; }
        }

        private IR_UserInfo_AcitonInfoRepository _R_UserInfo_AcitonInfoRepository;
        public IR_UserInfo_AcitonInfoRepository R_UserInfo_AcitonInfoRepository
        {
            get
            {
                if(_R_UserInfo_AcitonInfoRepository == null)
                {
                    _R_UserInfo_AcitonInfoRepository = new R_UserInfo_AcitonInfoRepository();
                }
                return _R_UserInfo_AcitonInfoRepository;
            }
            set { _R_UserInfo_AcitonInfoRepository = value; }
        }

        private IRoleRepository _RoleRepository;
        public IRoleRepository RoleRepository
        {
            get
            {
                if(_RoleRepository == null)
                {
                    _RoleRepository = new RoleRepository();
                }
                return _RoleRepository;
            }
            set { _RoleRepository = value; }
        }

        private IUserInfoRepository _UserInfoRepository;
        public IUserInfoRepository UserInfoRepository
        {
            get
            {
                if(_UserInfoRepository == null)
                {
                    _UserInfoRepository = new UserInfoRepository();
                }
                return _UserInfoRepository;
            }
            set { _UserInfoRepository = value; }
        }
    }    

DbSession.cs

 public partial class DbSession:IDbSession
    {
        //public ObjectContext DbContext = new HeimaShopDBEntities();//EF上下文实例怎么进行管理:保证线程内唯一
       public ObjectContext DbContext = DbContentFactory.GetCurrentDbContext();
        public int ExcuteSql(string sql, params ObjectParameter[] Parameters)
        {
            return DbContext.ExecuteFunction(sql, Parameters);
        }

        public int SaveChanges()//可以写一个批量保存,最后保存下,别的DAL层可以不写保存,把DAL的SaveChanges()提高倒也BLL层
        {
            return DbContext.SaveChanges();
        }
    }

BaseRepository.cs

public  class BaseRepository<T> where T:class
    {
        //public HeimaShopDBEntities db = new HeimaShopDBEntities();
         public ObjectContext db = DbContentFactory.GetCurrentDbContext();
        /// <summary>
        /// 查询
        /// </summary>
        /// <param name="whereLambda"></param>
        /// <returns></returns>
        public IQueryable<T> LoadEntities(Func<T, bool> whereLambda)
        {
            return db.CreateObjectSet<T>().Where<T>(whereLambda).AsQueryable();
        }
        /// <summary>
        /// 分页
        /// </summary>

        public IQueryable<T> LoadPageEntities<S>(int pageSize, int pageIndex, out int total, Func<T, bool> whereLambda, Func<T, S> orderByLambda, bool isAsc)
        {
            var temp = db.CreateObjectSet<T>().Where<T>(whereLambda);
            total = temp.Count();
            if (isAsc)
            {
                temp = temp.OrderBy<T, S>(orderByLambda).Skip<T>((pageIndex - 1) * pageSize).
                    Take<T>(pageSize);
            }
            else
            {
                temp = temp.OrderByDescending(orderByLambda).Skip<T>((pageIndex - 1) * pageSize).Take<T>(pageSize);

            }
            return temp.AsQueryable();
        }
        /// <summary>
        /// 添加
        /// </summary>

        public T AddEntity(T entity)
        {
            db.CreateObjectSet<T>().AddObject(entity);
            //db.SaveChanges();
            return entity;
        }
        /// <summary>
        /// 删
        /// </summary
        public bool DeleteEntity(T entity)
        {
            db.CreateObjectSet<T>().Attach(entity);
            db.ObjectStateManager.ChangeObjectState(entity, System.Data.EntityState.Deleted);
            //return db.SaveChanges() > 0;
            return true;
        }

        /// <summary>
        /// 更新
        /// </summary
        public bool UpdateEntity(T entity)
        {
            db.CreateObjectSet<T>().Attach(entity);
            db.ObjectStateManager.ChangeObjectState(entity, System.Data.EntityState.Modified);
            //db.SaveChanges();
            return true;
        }
    }

DbContentFactory.cs

 /// <summary>
    /// 实现对EF上下文实例进行管理,保证线程内唯一
    /// </summary>
   public  class DbContentFactory
    {
        //CallContext 是类似于方法调用的线程本地存储区的专用集合对象,并提供对每个逻辑执行线程都唯一的数据槽。 数据槽不在其他逻辑线程上的调用上下文之间共享。 当 CallContext 沿执行代码路径往返传播并且由该路径中的各个对象检查时,可将对象添加到其中。
       public static ObjectContext GetCurrentDbContext()
       {
           ObjectContext context = (ObjectContext)CallContext.GetData("DbContext");
           if (context == null)
           {
               context = new HeimaShopDBEntities();
               CallContext.SetData("DbContext", context);//要存储在调用上下文中的对象,1名字,2对象
           }
           return context;
       }
    }

DbSessionFactory.cs

public class DbSessionFactory
    {
       /// <summary>
       /// 保证DbSession的实例是线程内唯一的
       /// </summary>
       /// <returns></returns>
       public static IDbSession GetCurrentDbSession() { 
       //从线程内数据槽获取数据,保证线程内数据不被其它线程所访问到
           IDbSession dbSession = (IDbSession)CallContext.GetData("DbSession");
           if (dbSession == null) 
           {
               dbSession = new DbSession();
               CallContext.SetData("DbSession", dbSession);
           }
           return dbSession;
       }
    }

Repository.tt生成的cs

public partial class ActionGroupRepository :BaseRepository<ActionGroup>,IActionGroupRepository
    {}

    public partial class ActionInfoRepository :BaseRepository<ActionInfo>,IActionInfoRepository
    {}

    public partial class DepartmentRepository :BaseRepository<Department>,IDepartmentRepository
    {}

    public partial class ProductRepository :BaseRepository<Product>,IProductRepository
    {}

    public partial class R_UserInfo_AcitonInfoRepository :BaseRepository<R_UserInfo_AcitonInfo>,IR_UserInfo_AcitonInfoRepository
    {}

    public partial class RoleRepository :BaseRepository<Role>,IRoleRepository
    {}

    public partial class UserInfoRepository :BaseRepository<UserInfo>,IUserInfoRepository
    {}

UserInfoRepository.cs

  public partial class UserInfoRepository : BaseRepository<UserInfo>, IUserInfoRepository
    {

    }

BLL

IServices.tt

    public partial class ActionGroupService :BaseService<ActionGroup>,IActionGroupService
    {
        public override void SetCurrentReposiotry()
        {
            CurrentReposiotry = this.DbSession.ActionGroupRepository;
        }
    }   

    public partial class ActionInfoService :BaseService<ActionInfo>,IActionInfoService
    {
        public override void SetCurrentReposiotry()
        {
            CurrentReposiotry = this.DbSession.ActionInfoRepository;
        }
    }   

    public partial class DepartmentService :BaseService<Department>,IDepartmentService
    {
        public override void SetCurrentReposiotry()
        {
            CurrentReposiotry = this.DbSession.DepartmentRepository;
        }
    }   

    public partial class ProductService :BaseService<Product>,IProductService
    {
        public override void SetCurrentReposiotry()
        {
            CurrentReposiotry = this.DbSession.ProductRepository;
        }
    }   

    public partial class R_UserInfo_AcitonInfoService :BaseService<R_UserInfo_AcitonInfo>,IR_UserInfo_AcitonInfoService
    {
        public override void SetCurrentReposiotry()
        {
            CurrentReposiotry = this.DbSession.R_UserInfo_AcitonInfoRepository;
        }
    }   

    public partial class RoleService :BaseService<Role>,IRoleService
    {
        public override void SetCurrentReposiotry()
        {
            CurrentReposiotry = this.DbSession.RoleRepository;
        }
    }   

    public partial class UserInfoService :BaseService<UserInfo>,IUserInfoService
    {
        public override void SetCurrentReposiotry()
        {
            CurrentReposiotry = this.DbSession.UserInfoRepository;
        }
    }

BaseService.cs

public abstract class BaseService<T> where T:class,new() //构造函数
    {
        public IDbSession DbSession 
        {
            get { return DbSessionFactory.GetCurrentDbSession(); }
        }
        /// <summary>
        /// 基类中直接调用此抽象方法,那么必须在子类中实现
        /// </summary>
        public BaseService() {
            SetCurrentReposiotry();
        }

        /// <summary>
        /// 当前仓储
        /// </summary>
        public IBaseRepository<T> CurrentReposiotry
        {
            get;
            set;
        }
        /// <summary>
        /// 设置下当前的仓储
        /// </summary>
        public abstract void SetCurrentReposiotry();

        //最基本的crud方法
        public virtual IQueryable<T> LoadEntities(Func<T, bool> whereLambda)
        {
            //调用数据库访问层来实现  过滤查询
            //这个地方我们不知当前仓储是谁。那么就调用 当前仓储的属性
            return CurrentReposiotry.LoadEntities(whereLambda);
        }
        /// <summary>
        /// 分页
        /// </summary>
        public IQueryable<T> LoadPageEntities<S>(int pageSize, int pageIndex, out int total, Func<T, bool> whereLambda, Func<T, S> orderByLambda, bool isAsc)
        {
            return CurrentReposiotry.LoadPageEntities<S>(pageSize, pageIndex, out total, whereLambda, orderByLambda, isAsc);
        }
        /// <summary>
        /// 添加
        /// </summary>
        public T AddEntity(T entity)
        {
            CurrentReposiotry.AddEntity(entity);
            DbSession.SaveChanges();
            return entity;
        }
        /// <summary>
        /// 删除
        /// </summary>
        public bool DeleteEntity(T entity)
        {
            //return CurrentReposiotry.DeleteEntity(entity);
            CurrentReposiotry.DeleteEntity(entity);
            return DbSession.SaveChanges() > 0;

        }
        /// <summary>
        /// 修改
        /// </summary>
        public bool UpdateEntity(T entity)
        {
            //return CurrentReposiotry.UpdateEntity(entity);
            CurrentReposiotry.UpdateEntity(entity);
           return DbSession.SaveChanges() > 0;
        }
    }

UserInfoService.cs

  public partial class UserInfoService : BaseService<UserInfo>,IUserInfoService
    {
       // public override void SetCurrentReposiotry()
       //{
       //    CurrentReposiotry = this.DbSession.UserInfoRepository;
       //}
        #region 多条件查询
        public IQueryable<UserInfo> LoadUsers(UserInfoSearchParam param)
        {
            //先过滤,在分页

            var temp = DbSession.UserInfoRepository.LoadEntities(u => true);//会延迟加载
            if (!string.IsNullOrEmpty(param.Email))
            {
                temp = temp.Where<UserInfo>(u => u.Email.Contains(param.Email));
            }
            if (!string.IsNullOrEmpty(param.UserName))
            {
                temp = temp.Where<UserInfo>(u => u.UserName.Contains(param.UserName));
            }
            param.Total = temp.Count();
            return temp.OrderByDescending(u => u.ID).Skip<UserInfo>((param.PageIndex - 1) * param.PageSize).Take<UserInfo>(param.PageSize).AsQueryable();
        } 
        #endregion

        #region 批量删除
        public int DeleteUsers(List<int> listIds)
        {
            var Users = DbSession.UserInfoRepository.LoadEntities(a => listIds.Contains(a.ID));
            foreach (var user in Users)
            {
                DbSession.UserInfoRepository.DeleteEntity(user);
            }

            return DbSession.SaveChanges();
        } 
        #endregion
    }

上一篇
上传与下载 上传与下载
上传与下载听说好多面试的时候喜欢出上传与下载的题目,这里我就写winform版本和.net版本都写一个,写核心代码,细节就不写了,仅供参考 Form //上传 private void btnUpload_Click(ob
2019-01-17
下一篇
构造函数 构造函数
构造函数构造函数主要是用来创建对象时为对象赋初值来初始化对象。总与new运算符一起使用在创建对象的语句中 。A a=new A(); 构造函数具有和类一样的名称;但它是一个函数具有函数的所有特性,同一个类里面可以有多个参数不同的构造函数,也
2019-01-16
目录