1.第一步
创建MVC项目在Views的Home控制器下添加login登录页面
2.第二步创建实体层先创建项目选用类库.(NET Framwork)在新项目内添加新项目选中ADO.NET数据模型点击添加
3.第三步创建数据访问层也是先创建项目选用类库.(NET Framwork)在新项目内添加新项目选中EE 6.x DbContext生成器
在Model1.Context.tt类里修改一下其中的代码
<#@ template language="C#" debug="false" hostspecific="true"#>
<#@ include file="EF.Utility.CS.ttinclude"#>
<#@ output extension=".cs"#>
<#
CodeGenerationTools code = new CodeGenerationTools(this);
MetadataLoader loader = new MetadataLoader(this);
CodeRegion region = new CodeRegion(this, 1);
MetadataTools ef = new MetadataTools(this);
string inputFile = @"C:\Mfan\MyZ\MyZ.Model\Model1.edmx"; //你所创建的实体类的Model1.edmx路径
EdmItemCollection ItemCollection = loader.CreateEdmItemCollection(inputFile);
string namespaceName = code.VsNamespaceSuggestion();
EntityFrameworkTemplateFileManager fileManager = EntityFrameworkTemplateFileManager.Create(this);
#>
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using MyZ.Repository;
namespace MyZ.Repository
{
<#
foreach (EntityType entity in ItemCollection.GetItems().OrderBy(e => e.Name))
{
#>
public partial class <#=entity.Name#>Repository : BaseRepository<<#=entity.Name#>,PermissionEntities> //创建连接数据库的名字
{
}
<#}#>
}
在创建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 MyZ.Repository
{
public class BaseRepository where T:class
where TS:DbContext, new()
{
//当前操作的数据库实例
private DbContext db = DbContextory.GetCurrenDbContext();
#region 单表添加一条记录
///
/// 单表添加一条记录
///
///
///
public bool Add(T entity)
{
//using (var db=new PermissionsEntities())
//{
db.Set().Add(entity);
return db.SaveChanges() > 0;
//}
}
#endregion
#region 单表添加多条记录
///
/// 单表添加多条记录
///
///
///
public bool AddRange(List entitys)
{
db.Set().AddRange(entitys);
return db.SaveChanges() > 0;
}
#endregion
#region 删除
///
/// 删除
///
///
///
public bool Delete(T entity)
{
db.Entry(entity).State = EntityState.Deleted;
return db.SaveChanges() > 0;
}
#endregion
#region 删除一个集合
///
/// 删除一个集合
///
///
///
public bool BatchDelete(List entities)
{
db.Set().RemoveRange(entities);
return db.SaveChanges() > 0;
}
#endregion
#region 删除多个实体根据id
///
/// 删除多个实体根据id
///
///
///
public bool BatchDelete(params int[] ids)
{
foreach (var id in ids)
{
var entity = db.Set().Find(id);
if (entity != null)
db.Set().Remove(entity);
}
return db.SaveChanges() > 0;
}
#endregion
#region 修改
///
/// 修改
///
///
///
public bool Update(T entity)
{
db.Entry(entity).State = EntityState.Modified;
return db.SaveChanges() > 0;
}
#endregion
#region 查询返回一个集合
///
/// 查询返回一个集合
///
///
///
public List QueryList(Expression> lambdaExpression)
{
return db.Set().Where(lambdaExpression).ToList();
}
#endregion
#region 查询返回一个对象,没有返回null
///
/// 查询返回一个对象,没有返回null
///
///
///
public T Query(Expression> lambdaExpression)
{
return db.Set().SingleOrDefault(lambdaExpression);
}
#endregion
#region 判断是否存在
///
/// 判断是否存在
///
///
///
public bool Exists(Expression> lambdaExpression)
{
return db.Set().Any(lambdaExpression);
}
#endregion
#region 分页
///
/// 分页
///
///
///
///
///
///
///
///
///
public List QueryPageList(int pageIndex, int pageSize, Expression> whereLambda, Expression> orderbyLambda, out int count, bool isAsc = true)
{
count = db.Set().Where(whereLambda).Count();
if (!isAsc)
return db.Set().Where(whereLambda)
.OrderByDescending(orderbyLambda)
.Skip((pageIndex - 1) * pageSize)
.Take(pageSize)
.ToList();
return db.Set().Where(whereLambda)
.OrderBy(orderbyLambda)
.Skip((pageIndex - 1) * pageSize)
.Take(pageSize)
.ToList();
}
#endregion
}
}
4.第四步:在业务逻辑层内创建AdminService和BaseService类对应数据访问层
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using MyZ.Model;
namespace MyZ.Service
{
public class AdminService:BaseService
{
public AdminUser AdminLogin(AdminUser adminUser)
{
return Query(a => a.Name == adminUser.Name && a.Password == adminUser.Password);
}
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using MyZ.Model;
using MyZ.Repository;
namespace MyZ.Service
{
public class BaseService where T : class
{
//当前操作的数据库实例
private BaseRepository db = new BaseRepository();
#region 添加
///
/// 添加
///
///
///
public virtual bool Add(T entity, int role, int module)
{
return db.Add(entity);
}
//添加多条数据
public virtual bool AddRange(List entity)
{
return db.AddRange(entity);
}
#endregion
#region 删除
///
/// 删除单条
///
///
///
public virtual bool Delete(T entity)
{
return db.Delete(entity);
}
///
/// 删除多条
///
///
///
public virtual bool BatchDelete(List entitys)
{
return db.BatchDelete(entitys);
}
///
/// 根据ID删除多条
///
///
///
public virtual bool BatchDelete(params int[] ids)
{
return db.BatchDelete(ids);
}
///
/// 删除单个
///
///
///
//public virtual bool Delete(int id)
//{
// return db.Delete(id);
//}
#endregion
#region 修改
//修改
public virtual bool Update(T entity)
{
return db.Update(entity);
}
#endregion
#region 查询
///
/// 返回一个集合
///
///
///
public virtual List QueryList(Expression> lambdaExpression)
{
return db.QueryList(lambdaExpression);
}
///
/// 返回一个对象,一般根据主健不能查出两个,如果不存在返回默认值
///
///
///
public virtual T Query(Expression> lambdaExpression)
{
return db.Query(lambdaExpression);
}
///
/// 判断是否存在
///
///
///
public virtual bool Exists(Expression> lambdaExpression)
{
return db.Exists(lambdaExpression);
}
#endregion
#region 分页
///
/// 分页
///
///
///
///
///
///
///
///
///
public virtual List QueryPageList(int PageIndex, int PageSize, Expression> whereLambda, Expression> orderbyLambda, out int count, bool isAsc = true)
{
return db.QueryPageList(PageIndex, PageSize, whereLambda, orderbyLambda, out count, isAsc);
}
#endregion
}
}
5最后:在UI层内的Model添加AdminContext上下文类和OperatResult判断类然后在Login控制器写入login登录的代码
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.SessionState;
using MyZ.Model;
namespace MyZ.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 AdminUser adminUser
{
get
{
return httpSession[sessionKey] as AdminUser;
}
set
{
httpSession[sessionKey] = value;
}
}
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace MyZ.Web.Models
{
public class OperatResult
{
public bool Success { get; set; }
}
}
public JsonResult Query(AdminUser adminUser)
{
AdminService adminService = new AdminService();
OperatResult result = new OperatResult();
AdminUser user = adminUser;
Expression> lambdaExpression = a => a.Name == adminUser.Name && a.Password == adminUser.Password;
//调用业务层的lamdam表达式的记住密码
user = adminService.AdminLogin(user);
result.Success = adminService.Query(lambdaExpression) != null;
if (result.Success)
{
//创建Cookie对象
HttpCookie httpCookie = new HttpCookie("Admin");
httpCookie.Values.Add("Name", user.Name);
httpCookie.Values.Add("Password", user.Password);
//设置过期时间
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);
}
//在Home控制器下的Login里写入保存cookie的上下文
public ActionResult Login()
{
//取出Cookie保存的信息
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["pwd"];
//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.context.adminUser = new AdminUser()
{
Name = name,
Password = pwd
};
return Redirect("/Home/Index");
}
}
return View();
}
在页面中写入Ajax对应进行传输:
$(function () {
//页面加载刷新验证码
var show_num = [];
draw(show_num);
//点击图片刷新验证码
$("#canvas").on('click', function () {
draw(show_num);
})
$("#Login").click(function () {
var data = {};
data.Name = $("#name").val();
data.Password = $("#pwd").val();
//验证码校验
var val = $("#code").val().toLowerCase();
var num = show_num.join("");
if (val == '') {
layer.alert('请输入验证码!');
} else if (val != num) {
layer.alert('验证码错误!请重新输入!');
$("#code").val('');
draw(show_num);
}
else {
$.ajax({
data: data,
type: "post",
url: "/Login/Query",
success: function (operateResult) {
if (operateResult.Success) {
layer.alert('登录成功!', {
title: '提示框',
icon: 1,
});
location.href = "/Home/Index";
layer.close(index);
} else {
layer.alert('登录失败!', {
title: '提示框',
icon: 1,
});
}
}
})
}
})
});
@using MyZ.Web.Models
H-ui.admin v3.1