首先先在数据库中新建一个Login表
然后搭建EF框架 ——>利用vs2019先新建一个Web,在Web里面建一个类库Model,引入Ado.Net实体数据模型
再新建数据访问层的类库(DAL)——> 引入BaseRepository和DbContextFactory
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
}
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);
dbContext.Database.Log = s =>
{
//调用日志控件记录日志
};
return dbContext;
}
}
TestRepository.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 = @"..\\MJ.Model\TestModel.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 MJ.Model;
namespace MJ.DAL
{
<#
foreach (EntityType entity in ItemCollection.GetItems<EntityType>().OrderBy(e => e.Name))
{
#>
public partial class <#=entity.Name#>Repository : BaseRepository<<#=entity.Name#>,TestEntities>
{
}
<#}#>
}
注:记得修改Model.edmx、实体类引入的包、命名空间的值
在新建一个业务逻辑层的类库——>添加一个BaseService类
public class BaseService<T> where T : class, new()
{
//数据访问层
private readonly BaseRepository<T, TestEntities> baseRepository = new BaseRepository<T, TestEntities>();
#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
}
再新建一个LoginService,继承BaseService类
注:在每一个App.Config文件中都必须加上连接数据库的连接字符
最后就到了UI层了,在控制器中写入:
/// <summary>
/// 验证登录
/// </summary>
/// <returns></returns>
public JsonResult ValidateLogin(Login login, bool ischecked)
{
operateResult.Success = loginService.Exists(a => a.username == login.username && a.password == login.password);
if (operateResult.Success)
{
if (operateResult.Success)
{
UserContext.context.login = login;
}
if (ischecked)
{
//Cookie
HttpCookie cookie = new HttpCookie("key"); //创建Cookie ("随便取名")
cookie["key"] = login.username;
cookie.Expires = DateTime.Now.AddDays(1); //设置Cookie时间为1天
//添加Cookie到浏览器
System.Web.HttpContext.Current.Response.Cookies.Add(cookie);
}
}
return Json(operateResult);
}
在Login页面中写入Ajax
注:记得引入Layui的js和css哦!