1.新建Mvc项目,将页面模板考入,添加css,js等 控制器添加视图方法 添加Nuget程序包entity Framwork
2.创建类库,model实体类,右键添加新建项,选择Ado.Net实体数据模型,选择来自数据库的ef设计器,选择新建连接,输入服务器名localhost ,身份验证选择sql server验证,输入sql server账号密码,选择数据库名,确认后选择实体框架6.x ,选择所需要的表,点击完成即可自动生成。
3.配置数据库连接 在web.config和实体类的app.config中添加以下代码,需修改模型名字,数据库名,账号以及密码
<connectionStrings>
<add name="实体模型名字" connectionString="metadata=res://*/Model1.csdl|res://*/Model1.ssdl|res://*/Model1.msl;provider=System.Data.SqlClient;provider connection string="data source=.;initial catalog=Newp;persist security info=True;user id=sa;password=sasa;MultipleActiveResultSets=True;App=EntityFramework"" providerName="System.Data.EntityClient" />
</connectionStrings>
4.创建类库,DAL数据访问层,添加引用,管理Nuget程序包,搜索Entity Framwork ,安装包。
创建DbContextFactory
public class DbContextFactory<TS> where TS : DbContext, new()
{
/// <summary>
/// 唯一实例获取
/// </summary>
/// <returns></returns>
public static DbContext GetCurrentDbContext()
{
var dbContext = CallContext.GetData(typeof(TS).Name) as DbContext;
if (dbContext != null)
return dbContext;
dbContext = new TS();
CallContext.SetData(typeof(TS).Name, dbContext);
return dbContext;
}
}
创建BaseRepository类 并且添加引用
public class BaseRepository<T, TS> where T : class, new()
where TS : DbContext, new()
{
private static DbContext Db
{
get
{
var dbContext = DbContextFactory<TS>.GetCurrentDbContext();
return dbContext;
}
}
#region 添加数据
public virtual bool Add(T entity)
{
Db.Set<T>().Add(entity);
return Db.SaveChanges() > 0;
}
public virtual bool AddRange(List<T> entities)
{
Db.Set<T>().AddRange(entities);
return Db.SaveChanges() > 0;
}
#endregion
#region 修改数据
public virtual bool Update(T entity)
{
Db.Entry(entity).State = EntityState.Modified;
return Db.SaveChanges() > 0;
}
#endregion
#region 删除数据
public virtual bool Delete(T entity)
{
Db.Entry(entity).State = EntityState.Deleted;
return Db.SaveChanges() > 0;
}
public virtual bool BatchDelete(List<T> entities)
{
Db.Set<T>().RemoveRange(entities);
return Db.SaveChanges() > 0;
}
public virtual bool Delete(int id)
{
var entity = Db.Set<T>().Find(id);//如果实体已经在内存中,那么就直接从内存拿,如果内存中跟踪实体没有,那么才查询数据库。
if (entity != null) Db.Set<T>().Remove(entity);
return Db.SaveChanges() > 0;
}
public virtual bool BatchDelete(params int[] ids)
{
foreach (var item in ids)
{
var entity = Db.Set<T>().Find(item);//如果实体已经在内存中,那么就直接从内存拿,如果内存中跟踪实体没有,那么才查询数据库。
if (entity != null) Db.Set<T>().Remove(entity);
}
return Db.SaveChanges() > 0;
}
#endregion
#region 获取数据
public List<T> QueryList(Expression<Func<T, bool>> whereLambda)
{
return Db.Set<T>().Where(whereLambda).ToList();
}
public T Query(Expression<Func<T, bool>> whereLambda)
{
return Db.Set<T>().Where(whereLambda).SingleOrDefault();
}
public bool Exists(Expression<Func<T, bool>> whereLambda)
{
return Db.Set<T>().Where(whereLambda).Any();
}
public List<T> QueryPageList<S>(int pageIndex, int pageSize, Expression<Func<T, bool>> whereLambda, Expression<Func<T, S>> orderbyLambda, out int total, bool isAsc)
{
total = Db.Set<T>().Where(whereLambda).Count();
if (isAsc)
{
return
Db.Set<T>()
.Where(whereLambda)
.OrderBy(orderbyLambda)
.Skip(pageSize * (pageIndex - 1))
.Take(pageSize)
.ToList();
}
else
{
return
Db.Set<T>()
.Where(whereLambda)
.OrderByDescending(orderbyLambda)
.Skip(pageSize * (pageIndex - 1))
.Take(pageSize)
.ToList();
}
}
#endregion
}
修改Model.Context.tt文件,将以下代码覆盖Model.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 = @"..\\JiaHua.Permission.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 JiaHua.Permission.Model;
namespace JiaHua.Permission.Repository
{
<#
foreach (EntityType entity in ItemCollection.GetItems<EntityType>().OrderBy(e => e.Name))
{
#>
public partial class <#=entity.Name#>Repository : BaseRepository<<#=entity.Name#>,PermissionEntities>
{
}
<#}#>
}
修改以下代码
string inputFile = @"..\\JiaHua.Permission.Model\Model1.edmx";
//修改为你的命名空间
string inputFile = @"..\\Oc.sixth.Model\Model1.edmx";
using JiaHua.Permission.Model;
//修改为你的项目命名空间
using Oc.sixth.Model;
public partial class <#=entity.Name#>Repository : BaseRepository<<#=entity.Name#>,NewpEntities>
{
}
//将NewpEntities 改成你的数据库模型名字
记得添加引用
5.创建类库,BLL业务逻辑层,添加一个类,BaseService
public class BaseService<T> where T : class, new()
{
//数据访问层
private readonly BaseRepository<T, NewpEntities> baseRepository = new BaseRepository<T, NewpEntities>();
#region 添加
/// <summary>
/// 单表的添加一条记录
/// </summary>
/// <param name="entity"></param>
/// <returns></returns>
public virtual bool Add(T entity)
{
return baseRepository.Add(entity);
}
/// <summary>
/// 单表的添加多条记录
/// </summary>
/// <param name="entities"></param>
/// <returns></returns>
public virtual bool AddRange(List<T> entities)
{
return baseRepository.AddRange(entities);
}
#endregion
#region 修改
/// <summary>
/// 修改
/// </summary>
/// <param name="entity"></param>
/// <returns></returns>
public virtual bool Update(T entity)
{
return baseRepository.Update(entity);
}
#endregion
#region 删除
/// <summary>
/// 删除单个实体
/// </summary>
/// <param name="entity"></param>
/// <returns></returns>
public virtual bool Delete(T entity)
{
return baseRepository.Delete(entity);
}
/// <summary>
/// 删除单个实体
/// </summary>
/// <param name="entity"></param>
/// <returns></returns>
public virtual bool Delete(int id)
{
return baseRepository.Delete(id);
}
/// <summary>
/// 删除多个实体
/// </summary>
/// <param name="entities"></param>
/// <returns></returns>
public virtual bool BatchDelete(List<T> entities)
{
return baseRepository.BatchDelete(entities);
}
/// <summary>
/// 删除多个实体根据id
/// </summary>
/// <param name="ids"></param>
/// <returns></returns>
public virtual bool BatchDelete(params int[] ids)
{
return baseRepository.BatchDelete(ids);
}
#endregion
#region 查询
/// <summary>
/// 查询返回一个集合
/// </summary>
/// <param name="lambdaExpression"></param>
/// <returns></returns>
public virtual List<T> QueryList(Expression<Func<T, bool>> lambdaExpression)
{
return baseRepository.QueryList(lambdaExpression);
}
/// <summary>
/// 查询返回一个对象,没有返回null
/// </summary>
/// <param name="lambdaExpression"></param>
/// <returns></returns>
public virtual T Query(Expression<Func<T, bool>> lambdaExpression)
{
return baseRepository.Query(lambdaExpression);
}
/// <summary>
/// 判断是否存在
/// </summary>
/// <param name="lambdaExpression"></param>
/// <returns></returns>
public virtual bool Exists(Expression<Func<T, bool>> lambdaExpression)
{
return baseRepository.Exists(lambdaExpression);
}
/// <summary>
/// 分页
/// </summary>
/// <typeparam name="S"></typeparam>
/// <param name="pageIndex"></param>
/// <param name="pageSize"></param>
/// <param name="whereLambda"></param>
/// <param name="orderbyLambda"></param>
/// <param name="isAsc"></param>
/// <returns></returns>
public virtual List<T> QueryPageList<S>(int pageIndex, int pageSize, Expression<Func<T, bool>> whereLambda, Expression<Func<T, S>> orderbyLambda, out int count, bool isAsc = true)
{
return baseRepository.QueryPageList(pageIndex, pageSize, whereLambda, orderbyLambda, out count, isAsc);
}
#endregion
}
添加引用,添加entity farmwork包,修改以下代码
//数据访问层
private readonly BaseRepository<T, NewpEntities> baseRepository = new BaseRepository<T, NewpEntities>();
//将NewEntities 修改成你的数据库模型名字
6.添加UserInfoService类,继承BaseService类,
7.在web,models中添加OperateResult 和PageListResult类
public class OperateResult
{
public bool Success { get; set; }
}
public class PageListResult<T>
{
public int code { get; set; }
public string msg { get; set; }
public int count { get; set; }
public List<T> data { get; set; }
}
8.添加一个控制器,在里面写登录,
public class UserController : Controller
{
UserInfoService infoService = new UserInfoService();
// GET: User
public ActionResult Index()
{
return View();
}
public JsonResult Login(UserInfo userInfo, bool check)
{
OperateResult operate = new OperateResult();
UserInfo userinfos = new UserInfo();
Expression<Func<UserInfo, bool>> lambdaExpression = a => a.UserName == userInfo.UserName && a.UserPwd == userInfo.UserPwd;
userinfos = infoService.Query(lambdaExpression);
operate.Success = userinfos != null;
if (userinfos != null)
{
operate.Success = true;
//存储session值
AdminUserContext.current.userInfo = userinfos;
//如果选中保存密码则存储cookie
if (check)
{
//存储cookie
//创建一个Cookie对象
HttpCookie httpCookie = new HttpCookie("CookieName");
//设置Cookie的值
httpCookie.Values.Add("UserName", userinfos.UserName);
httpCookie.Values.Add("UserPwd", userinfos.UserPwd);
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);
}
}
home控制器中添加以下代码
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["UserPwd"];
//DateTime time = DateTime.Parse(cookie["DateTime"]);
if (name != null && pwd != null && DateTime.Parse(cookie["DateTime"]) != null && DateTime.Now < DateTime.Parse(cookie["DateTime"]))
{
//将Cookie中的值赋给上下文session 使其在不登录时页面也能够显示
AdminUserContext.current.userInfo = new UserInfo()
{
UserName = name,
UserPwd = pwd
};
return Redirect("/Home/Index");
}
}
return View();
}
修改login页面 并且加入jqueny
<script>
$(function () {
$("#login").click(function () {
var flag = false;
if ($("#checkpwd").is(":Checked")) { flag = true; }
var date = {}
date.UserName = $("#name").val();
date.UserPwd = $("#password").val();
$.ajax({
url: "/User/Login?check=" + flag,
data: date,
type: "post",
success: function (res) {
if (res.Success) {
alert("登录成功");
window.location.href = "/Home/Index";
} else {
alert("登录失败");
}
}
})
})
})
</script>
9.首页欢迎
在index页面中添加
@using Oc.sixth.Models;
@{
ViewBag.Title = "Home Page";
var admin = AdminUserContext.current.userInfo;
}
<h1>欢迎:@admin.Name</h1>