1.数据库设计
CREATE TABLE [dbo].[AdminUser](
[Id] [int] IDENTITY(1,1) NOT NULL,
[Name] [varchar](50) NULL,
[Password] [varchar](36) NULL,
[Email] [varchar](200) NULL
)
2.搭建MVC框架
3.创建实体类
先使用NuGet包添加引用 EntityFramework
使用ADO.NET实体数据模型(在新建项目中右键添加类中查找)
添加一个Operate类用来判断值
public class Operate
{
public bool Success { get; set; }
}
4.创建数据访问层
使用NuGet包添加引用 EntityFramework
使用类库中的EF 6.x DbContext生成器生成数据访问层
在自动生成的Model1.Context.tt里面的代码删除
修改成下方的代码
<#@ template language="C#" debug="false" hostspecific="true"#>
<#@ include file="EF.Utility.CS.ttinclude"#><#@
output extension=".cs"#>
<#
MetadataLoader loader = new MetadataLoader(this);
string inputFile = @"..\\Admin.Mode\Model1.edmx";//地址修改成自己的实体类的路径
EdmItemCollection ItemCollection = loader.CreateEdmItemCollection(inputFile);
#>
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Admin.Mode;//修改成自己的实体类的命名空间
namespace Admin.Mode//修改成自己的数据访问层的命名空间
{
<#
foreach (EntityType entity in ItemCollection.GetItems().OrderBy(e => e.Name))
{
#>
public partial class <#=entity.Name#>Repository : BaseRepository<<#=entity.Name#>,PermissionEntities>//BaseRepository、PermissionEntities下面图片说明
{
}
<#}#>
}
在PermissionEntities:在Model1.Context.cs名称复制过来就行了
BaseRepository:在数据访问层中添加一个基类,写相应的方法
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();
}
}
}
5.创建业务逻辑层
使用NuGet包添加引用 EntityFramework
在业务逻辑层中添加BaseService基类(相应的代码如下)
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);
}
}
在数据访问层中创建一个UserService类
public class UserService : BaseService, IDenpendecy
{
}
6.IU层
使用NuGet包添加引用 EntityFramework
在Models中创建一个上下文AdminContext如图下:
///
/// 管理员的上下文
///
public class AdminContext
{
///
/// 会话的key
///
private string SessionKey = "ADMIN_KEY";
///
/// 静态的上下文
///
public static AdminContext adminContext = new AdminContext();
///
///会话状态
///
public HttpSessionState httpSessionState => HttpContext.Current.Session;
///
/// 用户对象
///
public AdminUser adminInfo
{
get
{
return httpSessionState[SessionKey] as AdminUser;
}
set
{
httpSessionState[SessionKey] = value;
}
}
}
在View文件夹下的Login登录页面中使用.ajax跳转控制器调方法,相应代码如下:
后台登录 - H-ui.admin v3.1
记住密码
在Controller文件夹下创建一个控制器写个登陆方法(保存Cookie和session值),相应代码如下:
public class LoginController : Controller
{
private AdminInfoService adminInfoService = new AdminInfoService();
#region 登录
public JsonResult Login(AdminUser adminUser,bool check)
{
Operate operate = new Operate();
AdminUser adminUsers = new AdminUser();
Expression> lambdaExpression = a => a.Name == adminUser.Name && a.Password == adminUser.Password;
adminUsers = adminInfoService.Query(lambdaExpression);
operate.Success = adminUsers != null;
if (adminUsers != null)
{
operate.Success = true;
//存储session值
AdminContext.adminContext.adminInfo = adminUsers;
//如果选中保存密码则存储cookie
if (check)
{
//存储cookie
//创建一个Cookie对象
HttpCookie httpCookie = new HttpCookie("CookieName");
//设置Cookie的值
httpCookie.Values.Add("Name", adminUsers.Name);
httpCookie.Values.Add("Password", adminUsers.Password);
httpCookie.Values.Add("DateTime", DateTime.Now.AddDays(7).ToString("yyyy-MM-dd HH:mm:ss"));
//设置Cookie的过期时间
httpCookie.Expires = DateTime.Now.AddDays(7);
System.Web.HttpContext.Current.Response.Cookies.Add(httpCookie);
}
}
return Json(operate);
}
#endregion
}
在Controller文件夹下的Home控制器中的Login方法中去判断是否存在cookie值
public ActionResult Login()
{
//取出Cookie保存的信息
HttpCookie cookie = System.Web.HttpContext.Current.Request.Cookies.Get("CookieName");
if (cookie != null)
{
string name = cookie["Name"];//等同于string name = cookie.Values.Get("UserName");
string pwd = cookie["Password"];
//DateTime time = DateTime.Parse(cookie["DateTime"]);
if (name != null && pwd != null && DateTime.Parse(cookie["DateTime"]) != null && DateTime.Now < DateTime.Parse(cookie["DateTime"]))
{
//将Cookie中的值赋给上下文session 使其在不登录时页面也能够显示
AdminContext.adminContext.adminInfo = new AdminUser()
{
Name = name,
Password = pwd
};
return Redirect("/Home/Index");
}
}
return View();
}
View文件下的Index页面中去拿session值欢迎登陆
使用上下文中的值去欢迎登陆
var admin = AdminContext.adminContext.adminInfo;
@using Admin.Models;//自己的Models的引用
@{
var admin = AdminContext.adminContext.adminInfo;
}
H-ui.admin v3.1