1.新建项目,将页面模板及CSS ,js 加入Web项目中
2.创建类库Model,添加新建项类,选择ADO.NET实体数据模型


点击新建连接并配置,配置完成后选择是并进行下一步,选择实体框架6.x就行
配置Model的App.Config
<connectionStrings>
<add name="QAdminEntities" connectionString="metadata=res://*/Model1.csdl|res://*/Model1.ssdl|res://*/Model1.msl;provider=System.Data.SqlClient;provider connection string="data source=DESKTOP-GIMETHO;initial catalog=QAdmin;user id=sa;password=123456;MultipleActiveResultSets=True;App=EntityFramework"" providerName="System.Data.EntityClient" />
</connectionStrings>
2.在DAL访问层添加生成器

在Context文件中添加代码
<#@ 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 = @"..\\Web.Model\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 Model;
namespace Web.ManagerSys.Repository
{
<#
foreach (EntityType entity in ItemCollection.GetItems<EntityType>().OrderBy(e => e.Name))
{
#>
public partial class <#=entity.Name#>Repository : BaseRepository<<#=entity.Name#>,InfoManagerSyst emEntities>
{
}
<#}#>
}
配置完成Context文件后添加DbContextFactory
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Runtime.Remoting.Messaging;
using System.Text;
using System.Threading.Tasks;
namespace DAL
{
public class DbContextFactory<TS> where TS : DbContext, new()
{
public static DbContext GetCurrentDbContext()
{
var dbContext = CallContext.GetData(typeof(TS).Name) as DbContext;
if (dbContext != null)
{
return dbContext;
}
else
{
dbContext = new TS();
CallContext.SetData(typeof(TS).Name, dbContext);
return dbContext;
}
}
}
}
再生成BaseReposity通用访问代码
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 DAL
{
public class BaseRepository<T, TS> where T : class
where TS : DbContext, new()
{
private DbContext db = DbContextFactory<TS>.GetCurrentDbContext();
//添加单条记录
public bool Add(T entily)
{
db.Set<T>().Add(entily);
return db.SaveChanges() > 0;
}
//添加多条记录
public bool AddList(List<T> entily)
{
db.Set<T>().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<T> entiles)
{
db.Set<T>().RemoveRange(entiles);
return db.SaveChanges() > 0;
}
//根据id删除
public bool BatchDELETE(params int[] entiles)
{
foreach (var id in entiles)
{
var entity = db.Set<T>().Find(id);
if (entity != null)
{
db.Set<T>().Remove(entity);
}
}
return db.SaveChanges() > 0;
}
//修改
public bool Update(T entily)
{
db.Entry(entily).State = EntityState.Modified;
return db.SaveChanges() > 0;
}
//查询一个集合
public List<T> QueryList(Expression<Func<T, bool>> lambdaExpression)
{
return db.Set<T>().Where(lambdaExpression).ToList();
}
//查询一个对象,如果没有返回null
public T Query(Expression<Func<T, bool>> lambdaExpression)
{
return db.Set<T>().SingleOrDefault(lambdaExpression);
}
public bool Exists(Expression<Func<T, bool>> lambdaExpression)
{
return db.Set<T>().Any(lambdaExpression);
}
//分页查询
public List<T> QuerypageList<S>(int pageIndex, int pageSize, Expression<Func<T, bool>> wheredma, Expression<Func<T, S>> orderbyLamba, out int count, bool isAc = true)
{
count = db.Set<T>().Where(wheredma).Count();
if (!isAc)
{
return db.Set<T>().Where(wheredma).OrderByDescending(orderbyLamba).Skip((pageIndex - 1) * pageSize).Take(pageSize).ToList();
}
else
{
return db.Set<T>().Where(wheredma).OrderBy(orderbyLamba).Skip((pageIndex - 1) * pageSize).Take(pageSize).ToList();
}
}
}
}
在BLL中也新建BaseService实现访问逻辑
新建BaseService 中需要配置并添加引用 把T后的改成数据模型的名字
using DAL;
using Model;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Threading.Tasks;
public class BaseService<T> where T : class
{
private BaseRepository<T, QAdminEntities> baseRepository = new BaseRepository<T, QAdminEntities>();
using DAL;
using Model;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Threading.Tasks;
namespace BLL
{
public class BaseService<T> where T : class
{
private BaseRepository<T, QAdminEntities> baseRepository = new BaseRepository<T, QAdminEntities>();
//添加单条记录
public virtual bool Add(T entily)
{
return baseRepository.Add(entily);
}
//添加多条记录
public virtual bool AddList(List<T> entily)
{
return baseRepository.AddList(entily);
}
//删除
public virtual bool DELETE(T entily)
{
return baseRepository.DELETE(entily);
}
//删除多个
public virtual bool BDELETE(List<T> 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<T> QueryList(Expression<Func<T, bool>> lambdaExpression)
{
return baseRepository.QueryList(lambdaExpression);
}
//查询一个对象,如果没有返回null
public virtual T Query(Expression<Func<T, bool>> lambdaExpression)
{
return baseRepository.Query(lambdaExpression);
}
public virtual bool Exists(Expression<Func<T, bool>> lambdaExpression)
{
return baseRepository.Exists(lambdaExpression);
}
//分页查询
public virtual List<T> QuerypageList<S>(int pageIndex, int pageSize, Expression<Func<T, bool>> wheredma, Expression<Func<T, S>> orderbyLamba, out int count, bool isAc = true)
{
return baseRepository.QuerypageList(pageIndex, pageSize, wheredma, orderbyLamba, out count, isAc);
}
}
}
AdminUserService类
using Model;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace BLL
{
public class AdminUserService : BaseService<AdminUser>
{
#region 使用lambdam表达式
/// <summary>
/// 记住密码
/// </summary>
/// <param name="users"></param>
/// <returns></returns>
public AdminUser AdminByReader(AdminUser users)
{
return Query(a => a.UserName == users.UserName && a.UserPwd == users.UserPwd);
}
#endregion
}
}
UI层
AdminContext类(Models文件夹内)
using Model;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.SessionState;
namespace Web.Models
{
public class AdminContext
{
private const string sessionKey = "AdminInfo_session_Key";
public HttpSessionState httpSession => HttpContext.Current.Session;
/// <summary>
/// 设置静态 上下文
/// </summary>
public static AdminContext context = new AdminContext();
/// <summary>
/// 设置用户表
/// </summary>
public AdminUser adminUser
{
get
{
return httpSession[sessionKey] as AdminUser;
}
set
{
httpSession[sessionKey] = value;
}
}
}
}
ResultDataSet类(Models文件夹内)
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace Web.Models
{
/// <summary>
/// 分页
/// </summary>
/// <typeparam name="T"></typeparam>
public class ResultDataSet<T>
{
public int code { get; set; }
public string msg { get; set; }
public int count { get; set; }
public List<T> data { get; set; }
}
}
控制器(Controllers文件夹内)
AdminUserController类
using BLL;
using Model;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Web;
using System.Web.Mvc;
using Web.Models;
namespace Web.Controllers
{
public class AdminUserController : Controller
{
#region 登陆操作
/// <summary>
/// 登陆
/// </summary>
/// <param name="name"></param>
/// <param name="password"></param>
/// <returns></returns>
public JsonResult Query(AdminUser users)
{
AdminUserService adminUserService = new AdminUserService();
OperateResult result = new OperateResult();
AdminUser user = users;
Expression<Func<AdminUser, bool>> lambdaExpression = a => a.UserName == users.UserName && a.UserPwd == users.UserPwd;
//调用业务层的lamdam表达式的记住密码
user = adminUserService.AdminByReader(user);
result.Sussess = adminUserService.Query(lambdaExpression) != null;
if (result.Sussess)
{
//创建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();
// operateResult.Sussess = modueService.DELETE(infoManager);
// return Json(operateResult);
//}
/// <summary>
/// 去除session和cookie
/// </summary>
/// <returns></returns>
#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)
//{
// ModueService modueService = new ModueService();
// ResultDataSet<InfoManager> resultDataSet = new ResultDataSet<InfoManager>();
// resultDataSet.code = 0;
// resultDataSet.msg = string.Empty;
// resultDataSet.count = 0;
// int count = 0;
// List<InfoManager> modules = new List<InfoManager>();
// Expression<Func<InfoManager, bool>> whereLambda = a => true;
// Expression<Func<InfoManager, int>> orderbyLambda = a => a.ID;
// resultDataSet.data = modueService.QuerypageList(page, limit, whereLambda, orderbyLambda, out count);
// return Json(resultDataSet, JsonRequestBehavior.AllowGet);
//}
// GET: AdminUser
public ActionResult Index()
{
return View();
}
}
}
HomeController类(Controllers文件夹内)
using Model;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Web.Models;
namespace Web.Controllers
{
public class HomeController : Controller
{
public ActionResult Index()
{
return View();
}
public ActionResult About()
{
ViewBag.Message = "Your application description page.";
return View();
}
public ActionResult Contact()
{
ViewBag.Message = "Your contact page.";
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 AdminUser()
{
UserName = name,
UserPwd = pwd
};
return Redirect("/Home/Index");
}
}
return View();
}
}
}
Ul 页面验证登录
$("#login_btn").click(function () {
var data = {};
data.UserName = $("#username").val();
data.UserPwd = $("#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: "/AdminUser/Query",
success: function (result) {
if (result.Success) {
layer.alert('登录成功!', {
title: '提示框',
icon: 1,
});
location.href = "/Home/Index";
layer.close(index);
} else {
layer.alert('登录失败!', {
title: '提示框',
icon: 1,
});
}
}
})
}
})
});

1661

被折叠的 条评论
为什么被折叠?



