MVC使用EF实现后台登录首页以及列表增删改查

数据库设计

CREATE DATABASE [InfoManagerSystem]
GO
USE [InfoManagerSystem]
GO
/****** Object:  Table [dbo].[User]    Script Date: 10/15/2019 08:14:50 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[User](
	[UserName] [varchar](200) NOT NULL,
	[UserPwd] [varchar](200) NOT NULL
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
INSERT [dbo].[User] ([UserName], [UserPwd]) VALUES (N'Admin', N'Admin')
/****** Object:  Table [dbo].[InfoManager]    Script Date: 10/15/2019 08:14:49 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[InfoManager](
	[ID] [int] IDENTITY(1,1) NOT NULL,
	[Title] [varchar](200) NOT NULL,
	[Sort] [varchar](200) NOT NULL,
	[Source] [varchar](200) NOT NULL,
	[Browser] [bigint] NULL,
	[Status] [int] NULL
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
SET IDENTITY_INSERT [dbo].[InfoManager] ON
INSERT [dbo].[InfoManager] ([ID], [Title], [Sort], [Source], [Browser], [Status]) VALUES (1, N'老人与海', N'经典文学', N'湖南科技出版社', 2000, 1)
SET IDENTITY_INSERT [dbo].[InfoManager] OFF

创建MVC项目

MVC使用EF实现后台登录首页以及列表增删改查_第1张图片

MVC使用EF实现后台登录首页以及列表增删改查_第2张图片

MVC使用EF实现后台登录首页以及列表增删改查_第3张图片

三层搭建

MVC使用EF实现后台登录首页以及列表增删改查_第4张图片

创建分层并添加引用

实体层(Mode)

无引用,需要使用EntityFramework,使用NuGet安装

数据访问层(Dal)

引用实体层,需要使用EntityFramework,使用NuGet安装

业务逻辑层(Bll)

引用实体层,数据访问层,需要使用EntityFramework,使用NuGet安装

UI层(Web)

引用实体层,业务逻辑层,需要使用EntityFramework,使用NuGet安装

搭建完成后如图

MVC使用EF实现后台登录首页以及列表增删改查_第5张图片

登录HTML页面代码




    
    
    
    
    
    
    
    
    
    
    后台登录
    
    


    
    
username

主页HTML代码

@{
    Layout = null;
}
@using Zhongjiali.ManagerSys.Web.Models;
@using Zhongjiali.ManagerSys.Modles;

@{
    ViewBag.Title = "Home Page";
    var admin = AdminContext.context.adminUser;
}



    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
     
    
    
    H-ui.admin v3.1
    
    


    
    
    
    
  • 关闭当前
  • 关闭全部

Mode层

使用EF

MVC使用EF实现后台登录首页以及列表增删改查_第6张图片

MVC使用EF实现后台登录首页以及列表增删改查_第7张图片

MVC使用EF实现后台登录首页以及列表增删改查_第8张图片

MVC使用EF实现后台登录首页以及列表增删改查_第9张图片

搭建完成后自动生成的实体类如下

User类

namespace DaysGone.ManagerSys.Mode
{
    using System;
    using System.Collections.Generic;
    
    public partial class User
    {
        public string UserName { get; set; }
        public string UserPwd { get; set; }
    }
}

InfoManager类

namespace DaysGone.ManagerSys.Mode
{
    using System;
    using System.Collections.Generic;
    
    public partial class InfoManager
    {
        public int ID { get; set; }
        public string Title { get; set; }
        public string Sort { get; set; }
        public string Source { get; set; }
        public Nullable Browser { get; set; }
        public Nullable Status { get; set; }
    }
}

Result类

namespace DaysGone.ManagerSys.Mode
{
    public class OperateResult
    {
        public bool Success;
    }
}

数据访问层

数据访问层需要引用Mode层

BaseRepository类

using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Threading.Tasks;


namespace DaysGone.ManagerSys.Dal
{
    public class BaseRepository where T : class
                            where TS : DbContext, new()
    {
        private DbContext db = DbContextFactory.GetCurrentDbContext();


        //添加单条记录
        public bool Add(T entily)
        {
            db.Set().Add(entily);
            return db.SaveChanges() > 0;

        }

        //添加多条记录
        public bool AddList(List entily)
        {
            db.Set().AddRange(entily);
            return db.SaveChanges() > 0;

        }

        //删除
        public bool DELETE(T entily)
        {
            db.Entry(entily).State = EntityState.Deleted;
            return db.SaveChanges() > 0;

        }

        //删除多个
        public bool BDELETE(List entiles)
        {
            db.Set().RemoveRange(entiles);
            return db.SaveChanges() > 0;

        }

        //根据id删除
        public bool BatchDELETE(params int[] entiles)
        {
            foreach (var id in entiles)
            {
                var entity = db.Set().Find(id);
                if (entity != null)
                {
                    db.Set().Remove(entity);
                }
            }
            return db.SaveChanges() > 0;

        }
        //修改
        public bool Update(T entily)
        {
            db.Entry(entily).State = EntityState.Modified;
            return db.SaveChanges() > 0;
        }

        //查询一个集合
        public List QueryList(Expression> lambdaExpression)
        {
            return db.Set().Where(lambdaExpression).ToList();
        }

        //查询一个对象,如果没有返回null

        public T Query(Expression> lambdaExpression)
        {
            return db.Set().SingleOrDefault(lambdaExpression);
        }

        public bool Exists(Expression> lambdaExpression)
        {
            return db.Set().Any(lambdaExpression);
        }

        //分页查询
        public List QuerypageList(int pageIndex, int pageSize, Expression> wheredma, Expression> orderbyLamba, out int count, bool isAc = true)
        {
            count = db.Set().Where(wheredma).Count();
            if (!isAc)
            {
                return db.Set().Where(wheredma).OrderByDescending(orderbyLamba).Skip((pageIndex - 1) * pageSize).Take(pageSize).ToList();
            }
            else
            {
                return db.Set().Where(wheredma).OrderBy(orderbyLamba).Skip((pageIndex - 1) * pageSize).Take(pageSize).ToList();

            }
        }
    }
}

UserRepository类

	 public partial class UserRepository : BaseRepository
     {
		

     }	

InfoManagerRepository类

	 public partial class InfoManagerRepository : BaseRepository
    {
		

    }

业务逻辑层

BaseService类

using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Threading.Tasks;
using DaysGone.ManagerSys.DAL;
using DaysGone.ManagerSys.Mode;

namespace DaysGone.ManagerSys.Bll
{
    public class BaseService where T : class
    {
        private BaseRepository baseRepository = new BaseRepository();

        //添加单条记录
        public virtual bool Add(T entily)
        {

            return baseRepository.Add(entily);

        }

        //添加多条记录
        public virtual bool AddList(List entily)
        {
            return baseRepository.AddList(entily);
        }

        //删除
        public virtual bool DELETE(T entily)
        {
            return baseRepository.DELETE(entily);
        }

        //删除多个
        public virtual bool BDELETE(List entiles)
        {
            return baseRepository.BDELETE(entiles);
        }

        //根据id删除
        public bool BatchDELETE(params int[] entiles)
        {
            return baseRepository.BatchDELETE(entiles);
        }
        //修改
        public virtual bool Update(T entily)
        {

            return baseRepository.Update(entily);
        }

        //查询一个集合
        public virtual List QueryList(Expression> lambdaExpression)
        {
            return baseRepository.QueryList(lambdaExpression);
        }

        //查询一个对象,如果没有返回null

        public virtual T Query(Expression> lambdaExpression)
        {
            return baseRepository.Query(lambdaExpression);
        }

        public virtual bool Exists(Expression> lambdaExpression)
        {
            return baseRepository.Exists(lambdaExpression);
        }

        //分页查询
        public virtual List QuerypageList(int pageIndex, int pageSize, Expression> wheredma, Expression> orderbyLamba, out int count, bool isAc = true)
        {
            return baseRepository.QuerypageList(pageIndex, pageSize, wheredma, orderbyLamba, out count, isAc);
        }
    }
}

InfoManagerService类

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using DaysGone.ManagerSys.Mode;

namespace DaysGone.ManagerSys.Bll
{
    public class InfoManagerService : BaseService
    {
        public InfoManager SelectInfoMangers(int id)
        {
            return Query(a => a.ID == id);

        }
    }
}

AdminUserService类

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using DaysGone.ManagerSys.Mode;

namespace DaysGone.ManagerSys.Bll
{
   public class AdminUserService : BaseService
    {
        /// 
        /// 记住密码
        /// 
        /// 
        /// 
        public User AdminByReader(User users)
        {
            return Query(a => a.UserName == users.UserName && a.UserPwd == users.UserPwd);
        } 
    }
}

UI层

AdminContext类(Models文件夹内)

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.SessionState;
using DaysGone.ManagerSys.Modles;

namespace DaysGone.ManagerSys.Web.Models
{
    public class AdminContext
    {
        /// 
        /// 设置key值
        /// 
        private const string sessionKey = "AdminInfo_session_Key";
        public HttpSessionState httpSession => HttpContext.Current.Session;
        /// 
        /// 设置静态 上下文
        /// 
        public static AdminContext context = new AdminContext();
        /// 
        /// 设置用户表
        /// 

        public User adminUser
        {
            get
            {
                return httpSession[sessionKey] as User;
            }
            set
            {
                httpSession[sessionKey] = value;
            }
        }
    }
}

ResultDataSet类(Models文件夹内)

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace DaysGone.ManagerSys.Web.Models
{
    public class ResultDataSet
    {
        public int code { get; set; }
        public string msg { get; set; }
        public int count { get; set; }
        public List data { get; set; }
    }
}

过滤器(Attributes文件夹内)

行为过滤器(ActionAttribute)

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using DaysGone.ManagerSys.Web.Models;

namespace DaysGone.ManagerSys.Web.Attributes
{
   public class ActionAttribute : ActionFilterAttribute  //行为过滤器
    {
        /// 
        /// 调用控制器对应的Action方法之后的操作
        /// 
        /// 
        public override void OnActionExecuted(ActionExecutedContext filterContext)
        {
            if (AdminContext.context.adminUser != null)
            {
                //获取用户名
                string username = AdminContext.context.adminUser.UserName;
                string controller = filterContext.RouteData.Values["Controller"].ToString();
                string action = filterContext.RouteData.Values["Action"].ToString();
                //获取系统的日志
                string msg = $"时间:{DateTime.Now},用户名:{username},已完成控制器:{controller},页面:{action}";
                //获取文件路径
                string path = "D:\\lj.txt";
                File.AppendAllText(path, msg);
            }
               
        }


        /// 
        /// 调用控制器对应的Action方法之前的操作
        /// 
        /// 
        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            if (AdminContext.context.adminUser != null)
            {
                string username = AdminContext.context.adminUser.UserName;
                string controller = filterContext.RouteData.Values["Controller"].ToString();
                string action = filterContext.RouteData.Values["Action"].ToString();
                //获取系统的日志
                string msg = $"时间:{DateTime.Now},用户名:{username},正在操作控制器:{controller},页面:{action}";
                //获取文件路径
                string path = "D:\\Exception.txt";
                File.AppendAllText(path, msg);
            }

                //获取用户名
         
        }

        /// 
        /// 调用控制器对应的Action方法之后页面渲染之后的操作
        /// 
        /// 
        public override void OnResultExecuted(ResultExecutedContext filterContext)
        {

        }

        /// 
        /// 调用控制器对应的Action方法之后页面渲染之前的操作
        /// 
        /// 
        public override void OnResultExecuting(ResultExecutingContext filterContext)
        {

        }


    }
}

异常过滤器(ExceptionAttribute)

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace DaysGone.ManagerSys.Web.Attributes
{
    public class ExceptionAttribute : HandleErrorAttribute  //异常过滤器
    {
        /// 
        /// 系统发生异常的操作
        /// 
        /// 
        public override void OnException(ExceptionContext filterContext)
        {
            //Exception exception = filterContext.Exception;
            //string msg = exception.Message;

            //获取系统的日志
            string exception = filterContext.Exception.ToString();
            string msg = $"时间:{DateTime.Now},系统出错:{exception}";
            //获取文件路径
            string path = "D:\\Exception.txt";
            //如果文件不存在则创建
            /*if (!File.Exists(path))
            {
                File.Create(path);
            }*/
            File.AppendAllText(path, msg);
        }
    }
}

权限过滤器(PermissionAttribute)

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
using DaysGone.ManagerSys.Web.Models;

namespace DaysGone.ManagerSys.Web.Attributes
{
    public class PermissionAttribute : AuthorizeAttribute  //权限过滤器
    {
        /// 
        /// 判断认证是否通过
        /// 
        /// 
        /// 
        protected override bool AuthorizeCore(HttpContextBase httpContext)
        {
            //如果上下文不为空
            if (AdminContext.context.adminUser != null && httpContext.Session != null)
            {
                return true;
            }
            return false;

        }

        /// 
        ///认证不通过的时候所做的操作
        /// 
        /// 
        protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
        {
            //获取用户请求的地址
            string path = filterContext.HttpContext.Request.Path;

            //自定义路由跳转
            Dictionary keys = new Dictionary();
            keys.Add("Controller", "Home");
            keys.Add("Action", "Login");
            keys.Add("ReturnUrl", path);
            var routeValue = new RouteValueDictionary(keys);

            //根据指定路由跳转
            filterContext.Result = new RedirectToRouteResult(routeValue);

        }
    }
}

控制器(Controllers文件夹内)

AdminUserController类

using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Web;
using System.Web.Mvc;
using DaysGone.ManagerSys.Mode;
using DaysGone.ManagerSys.Bll;
using DaysGone.ManagerSys.Web.Models;

namespace DaysGone.ManagerSys.Web.Controllers
{
    public class AdminUserController : Controller
    {

        public JsonResult Add(InfoManager infoManager)
        {
            ModueService modueService = new ModueService();
            OperateResult operateResult = new OperateResult
            {
                Success = modueService.Add(infoManager)
            };
            return Json(operateResult);
        }

        //修改
        public JsonResult Update(InfoManager infoManager)
        {
            InfoManagerService infoManagerService = new InfoManagerService();
            OperateResult operateResult = new OperateResult
            {
                Success = infoManagerService.Update(infoManager)
            };
            return Json(operateResult);
        }

        #region 登陆操作
        /// 
        /// 登陆
        /// 
        /// 
        /// 
        /// 
        public JsonResult Query(User users)
        { 
            AdminUserService adminUserService = new AdminUserService();
            OperateResult result = new OperateResult();
            User user = users;
            Expression> lambdaExpression = a => a.UserName==users.UserName && a.UserPwd==users.UserPwd;
            //调用业务层的lamdam表达式的记住密码
            user= adminUserService.AdminByReader(user);
            result.Success = adminUserService.Query(lambdaExpression) != null;
            if(result.Success)
            {
                //创建Cookie对象
                HttpCookie httpCookie = new HttpCookie("CookieName");
                httpCookie.Values.Add("UserName", user.UserName);
                httpCookie.Values.Add("UserPwd", user.UserPwd);
               
                //设置过期时间
                httpCookie.Values.Add("time",DateTime.Now.AddDays(7).ToString());
                //添加Cookie对象
                System.Web.HttpContext.Current.Response.Cookies.Add(httpCookie);
            }
            //给上下文赋值
            AdminContext.context.adminUser = user;
            return Json(result);
        }
        #endregion

        //删除单条数据
        public JsonResult DELETE(InfoManager infoManager)
        {
            ModueService modueService = new ModueService();
            OperateResult operateResult = new OperateResult
            {
                Success = modueService.DELETE(infoManager)
            };
            return Json(operateResult);
        }


        /// 
        /// 去除session和cookie
        /// 
        /// 
        #region 去除session和cookie
        public ActionResult AdminOut()
        {
            //清除session
            AdminContext.context.adminUser = null;
            //获取cookie
            HttpCookie cok = Response.Cookies["UserName"];
            if (cok != null)
            {
                cok.Values.Clear();
            }
            return Redirect("/Home/login");
        }
        #endregion

        //分页查询
        public JsonResult GetMoudelList(int page, int limit)
        {
            InfoManagerService infoManagerService = new InfoManagerService();
            ResultDataSet resultDataSet = new ResultDataSet
            {
                code = 0,
                msg = string.Empty,
                count = 0
            };
            int count = 0;
            List modules = new List();
            Expression> whereLambda = a =>true;
            Expression> orderbyLambda = a => a.ID;
            resultDataSet.data = infoManagerService.QuerypageList(page, limit, whereLambda, orderbyLambda, out count);
            return Json(resultDataSet,JsonRequestBehavior.AllowGet);
        }
        // GET: AdminUser
        public ActionResult Index()
        {
            return View();
        }
    }
}

HomeController类(Controllers文件夹内)

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using DaysGone.ManagerSys.Mode;
using DaysGone.ManagerSys.Bll;
using DaysGone.ManagerSys.Web.Attributes;
using DaysGone.ManagerSys.Web.Models;

namespace DaysGone.ManagerSys.Web.Controllers
{
    public class HomeController : Controller
    {
        [PermissionAttribute]
        public ActionResult Index()
        {
            return View();
        }
        public ActionResult adminlist()
        {
            return View();
        }
        
       public ActionResult articleadd()
        {
            
            return View();
 
        }

        public ActionResult articlelist()
        {
            return View();
        }

        public ActionResult login()
        {
            HttpCookie cookie = System.Web.HttpContext.Current.Request.Cookies.Get("CookieName");
            if (cookie != null)
            {
                string name = cookie["UserName"];//等同于string name = cookie.Values.Get("UserName");
                string pwd = cookie["UserPwd"];
                DateTime time = DateTime.Parse(cookie["time"]);

                if (name != null && pwd != null && time != null && DateTime.Now < time)
                {
                    //将Cookie中的值赋给上下文session  使其在不登录时页面也能够显示
                    AdminContext.context.adminUser = new User()
                    {
                        UserName = name,
                        UserPwd = pwd
                    };
                    return Redirect("/Home/Index");
                }
            }






            return View();
        }

        public ActionResult About()
        {
            ViewBag.Message = "Your application description page.";

            return View();
        }

        public ActionResult Contact()
        {
            ViewBag.Message = "Your contact page.";

            return View();
        }
    }
}

 

你可能感兴趣的:(案例,学习笔记)