EF做后台登录+首页+记住密码

创建一个项目

使用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<EntityType>().OrderBy(e => e.Name))
{
#>
	 public partial class <#=entity.Name#>Repository : BaseRepository<<#=entity.Name#>,PermissionEntities>//BaseRepository、PermissionEntities下面图片说明
     {
		
     }	
<#}#>
	
}

PermissionEntities:在Model1.Context.cs这个里面的类的名称复制过来就行了

BaseRepository:在数据访问层中添加一个基类

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();
 
            }
        }
    }

然后创建业务逻辑层

使用NuGet包添加引用 EntityFramework

在业务逻辑层中添加BaseService基类

public class BaseService<T> where T : class
    {
        private BaseRepository<T, PermissionEntities1> baseRepository = new BaseRepository<T, PermissionEntities1>();
 
        //添加单条记录
        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);
        }
    }

在数据访问层中创建一个UserService

public class UserService : BaseService<AdminUser>, IDenpendecy
    {
    }

然后在UI层使用NuGet包添加引用 EntityFramework

再在Models中创建一个上下文AdminContext如图下:

在Login页面中使用.ajax跳转控制器调方法


<script type="text/javascript">
    //登录
    $("#den").on('click', function () {
        var flag = false;
        if ($("#checkpwd").is(":Checked")) { flag = true; }
        var AdminInfo = {};
        AdminInfo.Name = $("#name").val();
        AdminInfo.Password = $("#pwd").val();
 
        $.ajax({
            data: AdminInfo,
            type: "post",
            url: "/Login/Login?check=" + flag,
            success: function (operate) {
 
                if (operate.Success) {
                    alert("登录成功");
 
                    window.location.href = "/Home/Index";
 
                } else {
                    alert("登录失败");
                }
            }
        })
    })
</script>

创建一个控制器写个登陆方法(保存Cookiesession值)

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<Func<AdminUser, bool>> 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
    }

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();
        }

Index页面中去拿session值欢迎登陆

使用上下文中的值去欢迎登陆

var admin = AdminContext.adminContext.adminInfo;

@using Admin.Models;
@{
    var admin = AdminContext.adminContext.adminInfo;
}
<a href="#" class="dropDown_A">
    欢迎光临 @if (admin != null)
    {@admin.Name}
    <i class="Hui-iconfont">&#xe6d5;</i>
</a>
                           

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值