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

1.首先我们创建一个MVC项目

在这里插入图片描述

2.建立相应的文件夹和类库

在这里插入图片描述

3.在实体层 (添加类——>Ado.Net实体数据模型)

在这里插入图片描述

4.在数据访问层添加类——>EF 6.X DbContext生成器

在这里插入图片描述
在数据库中我们需要做一下修改
(1).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 = @"..\\Test1EF\Test1EF.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 Test1.EF.Dal;
 
namespace  Test1.EF.Dal
{
   
<#
foreach (EntityType entity in ItemCollection.GetItems<EntityType>().OrderBy(e => e.Name))
{
#>
	 public partial class <#=entity.Name#>Repository : BaseRepository<<#=entity.Name#>,entityFramework>
     {
		
     }	
<#}#>
	
}

注意:要修改4处改成自己的命名空间
(2.) 添加类 DbContextFactory

 public class DbContextFactory<TS> where TS : DbContext, new()
    {
        public static DbContext GetCarrentDcontext()
        {
            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;
        }
    }

(3.) 添加类 BaseRepository

  public class BaseRepository<T, TS> where T : class, new() where TS : DbContext, new()
        {
            private DbContext dbContext = DbContextFactory<TS>.GetCarrentDcontext();
            /// <summary>
            /// 通用单表添加方法
            /// </summary>
            /// <param name="entity"></param>
            /// <returns></returns>
            public bool Add(T entity)
            {
                dbContext.Set<T>().Add(entity);
                return dbContext.SaveChanges() > 0;
            }
            /// <summary>
            /// 通用单表删除方法
            /// </summary>
            /// <param name="entity"></param>
            /// <returns></returns>
            public bool Delete(T entity)
            {
                dbContext.Entry(entity).State = EntityState.Deleted;
                return dbContext.SaveChanges() > 0;
            }
            /// <summary>
            /// 通用单表批量删除,通过对象集合
            /// </summary>
            /// <param name="entityList"></param>
            /// <returns></returns>
            public bool Delete(List<T> entityList)
            {
                dbContext.Set<T>().RemoveRange(entityList);
                return dbContext.SaveChanges() > 0;
            }
            /// <summary>
            /// 通用单表批量删除,通过id集合
            /// </summary>
            /// <param name="ids"></param>
            /// <returns></returns>
            public bool Delete(List<int> ids)
            {
                foreach (var item in ids)
                {
                    var t = dbContext.Set<T>().Find(item);
                    dbContext.Set<T>().Remove(t);
                }
                return dbContext.SaveChanges() > 0;
            }
            /// <summary>
            /// 通用单表修改方法
            /// </summary>
            /// <param name="entity"></param>
            /// <returns></returns>
            public bool Update(T entity)
            {
                dbContext.Entry<T>(entity).State = EntityState.Modified;
                return dbContext.SaveChanges() > 0;
            }
            /// <summary>
            /// 返回一个数据集合
            /// </summary>
            /// <returns></returns>
            public List<T> QueryList(Expression<Func<T, bool>> lamdaExpression)
            {
                return dbContext.Set<T>().Where(lamdaExpression).ToList();
            }
            /// <summary>
            /// 返回单个对象
            /// </summary>
            /// <param name="lamdaExpression"></param>
            /// <returns></returns>
            public T Query(Expression<Func<T, bool>> lamdaExpression)
            {
                return dbContext.Set<T>().Where(lamdaExpression).SingleOrDefault();
            }
            /// <summary>
            /// 判断对象是否存在
            /// </summary>
            /// <param name="lamdaExpression"></param>
            /// <returns></returns>
            public bool Exist(Expression<Func<T, bool>> lamdaExpression)
            {
                return dbContext.Set<T>().Where(lamdaExpression).Any();
            }
            /// <summary>
            /// 分页查询
            /// </summary>
            /// <param name="pageIndex"></param>
            /// <param name="pageSize"></param>
            /// <param name="lamdaExpression"></param>
            /// <param name="orderBy"></param>
            /// <param name="count"></param>
            /// <param name="isAcs"></param>
            /// <returns></returns>
            public List<T> QueryPageList(int pageIndex, int pageSize, Expression<Func<T, bool>> lamdaExpression, Expression<Func<T, bool>> orderBy, out int count, bool isAcs = true)
            {
                count = dbContext.Set<T>().Where(lamdaExpression).Count();
                if (isAcs)
                {
                    return dbContext.Set<T>().Where(lamdaExpression)
                                             .OrderBy(orderBy)
                                             .Skip((pageIndex - 1) * pageSize)
                                             .Take(pageSize).ToList();
                }
                else
                {
                    return dbContext.Set<T>().Where(lamdaExpression)
                                             .OrderByDescending(orderBy)
                                             .Skip((pageIndex - 1) * pageSize)
                                             .Take(pageSize).ToList();
                }
            }
            /// <summary>
            /// 返回总记录数
            /// </summary>
            /// <param name="lamdaExpression"></param>
            /// <returns></returns>
            public int QueryCount(Expression<Func<T, bool>> lamdaExpression)
            {
                return dbContext.Set<T>().Where(lamdaExpression).Count();
            }

注意:在数据访问层右击——>管理NuGet程序包——>添加EntityFrameWork包

5.在业务逻辑层

(1)添加类BaseSerivces

 public class BaseSerivces<T> where T : class, new()
    {
        public BaseRepository<T, AdminPrivilegesEntities> baseRepository = new BaseRepository<T, AdminPrivilegesEntities>();

        /// <summary>
        /// 通用单表添加方法
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        public bool Add(T entity)
        {
            return baseRepository.Add(entity);
        }
        /// <summary>
        /// 通用单表删除方法
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        public bool Delete(T entity)
        {
            return baseRepository.Delete(entity);
        }
        /// <summary>
        /// 通用单表批量删除,通过对象集合
        /// </summary>
        /// <param name="entityList"></param>
        /// <returns></returns>
        public bool Delete(List<T> entityList)
        {
            return baseRepository.Delete(entityList);
        }
        /// <summary>
        /// 通用单表批量删除,通过id集合
        /// </summary>
        /// <param name="ids"></param>
        /// <returns></returns>
        public bool Delete(List<int> ids)
        {
            return baseRepository.Delete(ids);
        }
        /// <summary>
        /// 通用单表修改方法
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        public bool Update(T entity)
        {
            return baseRepository.Update(entity);
        }
        /// <summary>
        /// 返回一个数据集合
        /// </summary>
        /// <returns></returns>
        public List<T> QueryList(Expression<Func<T, bool>> lamdaExpression)
        {
            return baseRepository.QueryList(lamdaExpression);
        }
        /// <summary>
        /// 返回单个对象
        /// </summary>
        /// <param name="lamdaExpression"></param>
        /// <returns></returns>
        public T Query(Expression<Func<T, bool>> lamdaExpression)
        {
            return baseRepository.Query(lamdaExpression);
        }
        /// <summary>
        /// 判断对象是否存在
        /// </summary>
        /// <param name="lamdaExpression"></param>
        /// <returns></returns>
        public bool Exist(Expression<Func<T, bool>> lamdaExpression)
        {
            return baseRepository.Exist(lamdaExpression);
        }
        /// <summary>
        /// 分页查询
        /// </summary>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <param name="lamdaExpression"></param>
        /// <param name="orderBy"></param>
        /// <param name="count"></param>
        /// <param name="isAcs"></param>
        /// <returns></returns>
        public List<T> QueryPageList(int pageIndex, int pageSize, Expression<Func<T, bool>> lamdaExpression, Expression<Func<T, bool>> orderBy, out int count, bool isAcs = true)
        {
            return baseRepository.QueryPageList(pageIndex, pageSize, lamdaExpression, orderBy, out count);
        }
        /// <summary>
        /// 返回总记录数
        /// </summary>
        /// <param name="lamdaExpression"></param>
        /// <returns></returns>
        public int QueryCount(Expression<Func<T, bool>> lamdaExpression)
        {
            return baseRepository.QueryCount(lamdaExpression);
        }
    }

(2).添加引用位置在(packages\EntityFramework.6.2.0\lib\net45)

6.在我们UI层Views——>Home中建立视图把登录注册还有主页面放进去

在这里插入图片描述
(1)把js,cs的地址改成~/地址
(2) 在控制器写出对应的方法
(3)在Models文件夹里面创建一个类UserContext

 public class UserContext
    {
        public const string key = "lu";
        public static UserContext userContext = new UserContext();
        public HttpSessionState httpSessionState => HttpContext.Current.Session;
        public AdminUser adminUser
        {
            get
            {
                return this.httpSessionState[key] as AdminUser;
            }
            set
            {
                this.httpSessionState[key] = value;
            }
        }

    }

7.在控制器写方法

1.登录的方法

 public ActionResult Logic()
        {
            if (Models.UserContext.userContext.adminUser != null)
            {
                return RedirectToAction("Index", "Home");
            }
            var cookie = System.Web.HttpContext.Current.Request.Cookies[FormsAuthentication.FormsCookieName];
            if (cookie != null)
            {
                //获取存在的cookie
                var ticket = FormsAuthentication.Decrypt(cookie.Value);
                string userData = ticket.UserData;
                if (!string.IsNullOrEmpty(userData))
                {
                    //存储在session里面
                    AdminUser user = new AdminUser();
                    user.Id = Convert.ToInt32(userData.Split('#')[0]);
                    user.Name = userData.Split('#')[1];
                    Models.UserContext.userContext.adminUser = user;
                    return RedirectToAction("Index", "Home");
                }
            }
            return View();
        }

2.在页面登录页面写

  /// <summary>
        /// 登录
        /// </summary>
        /// <returns></returns>
        public JsonResult LogicAdmin(AdminUser adminUser,bool isa)
        {
            Ajaxs ajaxs = new Ajaxs();
            AdminUser adminUser1 = adminUserService.Query(a=>a.Name== adminUser.Name&a.Password== adminUser.Password);
            if (adminUser1!=null) {
                ajaxs.Success = true;
                Models.UserContext.userContext.adminUser = adminUser1;
                if (isa) {
                    string userData = adminUser1.Id + "#" + adminUser1.Name;
                    //数据放入ticket
                    FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(1, adminUser1.Name, DateTime.Now, DateTime.Now.AddMinutes(60), false, userData);
                    //数据加密
                    string enyTicket = FormsAuthentication.Encrypt(ticket);
                    HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName, enyTicket);
                    System.Web.HttpContext.Current.Response.Cookies.Add(cookie);
                }
            }
            else
            {
                ajaxs.Success = false;
            }
            return Json(ajaxs);
        }

8.在登录页面上写JS

 var data = {};
              data.Password = $("#userpwd").val();
              data.Name = $("#username").val();
               $.ajax({
                    url: "/Home/LogicAdmin?checkbox="+$("input[type='checkbox']").is(':checked'),
                    type: "Post",
                    data: data,
                    async: false,
                    success: function (data) {
                        if (data.Success) {
                            layer.close(index);
                            layer.msg('登陆成功!', {
                                title: '提示框',
                                icon: 1,
                                time: 300
                            }, function () {
                                    window.location.href = "/Home/Index";
                             });
                        }
                        else {
                            layer.close(index);
                            layer.msg('账户或密码错误!', {
                                title: '提示框',
                                icon: 1,
                                time: 500
                            });
                        }
                    }
                });
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值