EF框架实现登录(记住密码+首页欢迎)+列表功能(增删改查)+过滤器

一、登录

1、设计数据库

CREATE TABLE [dbo].[AdminUser](
	[Id] [int] IDENTITY(1,1) NOT NULL,
	[Name] [varchar](50) NULL,
	[Pwd] [varchar](36) NULL,
	[Email] [varchar](200) NULL
)

2、创建MVC框架

3、创建实体类–建立实体模型

创建Operate类

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace WebApplication4.Model
{
  public  class Operate
    {
        public bool Success { get; set; }

    }
}

右键–>添加类–>ADO.NET实体模型–>配置连接–>选择需要的数据库生成即可

效果:

4.创建数据库访问层–>生成EF6生成器

å¨è¿éæå¥å¾çæè¿°

效果:

添加EF引用:

引用-->右键-->NuGet包添加引用 EntityFramework

添加类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 WebApplication4.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();

            }
        }
    }

添加类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 WebApplication4.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;
            }
        }
    }

}

编辑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 = @"..\\WebApplication4.Model\Model1.edmx";  
EdmItemCollection ItemCollection = loader.CreateEdmItemCollection(inputFile);
#>
//注意修改相应的命名空间
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using WebApplication4.Model;
 
namespace WebApplication4.Model
{
   
<#
foreach (EntityType entity in ItemCollection.GetItems<EntityType>().OrderBy(e => e.Name))
{
#>
//注意PermissionEntities是实体模型中 : base("name=PermissionEntities")要改成相应的
	 public partial class <#=entity.Name#>Repository : BaseRepository<<#=entity.Name#>,PermissionEntities>
     {
		
     }	
<#}#>
	
}

4、业务逻辑层:

添加EF引用:

引用-->右键-->NuGet包添加引用 EntityFramework

在页面添加using引用

添加基类:BaseService类

using System;
using System.Collections.Generic;
using System.Linq.Expressions;
using WebApplication4.DAL;
using WebApplication4.Model;

namespace WebApplication4.BLL
{
    public class BaseService<T> where T : class
    {
        private BaseRepository<T, PermissionEntities> baseRepository = new BaseRepository<T, PermissionEntities>();

        //添加单条记录
        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);
        }
    }

}

5、创建业务逻辑层

添加AdminInfoService

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using WebApplication4.Model;

namespace WebApplication4.BLL.Service
{
    public class AdminInfoService : BaseService<AdminUser>
    {
    }
}

6、UI层
在Models文件夹添加上下文

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.SessionState;
using WebApplication4.Model;

namespace WebApplication4.Models
{
    /// <summary>
    /// 管理员的上下文
    /// </summary>
    public class AdminContext
    {
        /// <summary>
        /// 会话的key
        /// </summary>
        private string SessionKey = "ADMIN_KEY";

        /// <summary>
        /// 静态的上下文
        /// </summary>
        public static AdminContext adminContext = new AdminContext();

        /// <summary>
        ///会话状态
        /// </summary>
        public HttpSessionState httpSessionState => HttpContext.Current.Session;

        /// <summary>
        /// 用户对象
        /// </summary>
        public AdminUser adminInfo
        {
            get
            {
                return httpSessionState[SessionKey] as AdminUser;
            }
            set
            {
                httpSessionState[SessionKey] = value;
            }
        }
    }
}

创建一个空的控制器LoginController

using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Web;
using System.Web.Mvc;
using WebApplication4.BLL.Service;
using WebApplication4.Model;
using WebApplication4.Models;

namespace WebApplication4.Controllers
{
    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"));
     
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值