1 : 7 프로젝트를 만듭니다
2 : JiaHua.Market.Model는 물리 계층 관리 정보 클래스를 추가
/// <summary>
/// 管理员信息表
/// </summary>
public class AdminInfo
{
/// <summary>
/// 管理员Id
/// </summary>
[Key]
public int AdminId { get; set; }
/// <summary>
/// 真实姓名
/// </summary>
[MaxLength(50)]
public string RealName { get; set; }
/// <summary>
/// 登录名
/// </summary>
public string LoginName { get; set; }
/// <summary>
/// 登录密码
/// </summary>
public string LoginPwd { get; set; }
/// <summary>
/// 性别
/// </summary>
public short Sex { get; set; }
/// <summary>
/// 手机号
/// </summary>
public Int64 Telphone { get; set; }
/// <summary>
/// 邮箱
/// </summary>
public string Email { get; set; }
/// <summary>
/// 备注
/// </summary>
public string Remark { get; set; }
/// <summary>
/// 年龄
/// </summary>
public int Age { get; set; }
/// <summary>
/// 创建时间
/// </summary>
public DateTime CreateTime { get; set; }
/// <summary>
/// 最后一次登录时间
/// </summary>
public DateTime LastLoginTime { get; set; }
/// <summary>
/// 登录时间
/// </summary>
public DateTime LoginTime { get; set; }
/// <summary>
/// 修改时间
/// </summary>
public DateTime UpdateTime { get; set; }
/// <summary>
/// 状态1:启用 0:禁用
/// </summary>
public short Status { get; set; }
}
3 : Nuget 패키지를 설치 [참고 : 자신의 컴퓨터를 대신 netcore 버전 2.1.1]
Nuget의 선택 JiaHua.Market.Model 프로젝트는 패키지 관리자 콘솔 창은 다음과 같은 세 가지 명령을 입력하여 다음 :
설치 패키지 Microsoft.EntityFrameworkCore.SqlServer -version 2.1.1
설치 - 패키지 Microsoft.EntityFrameworkCore.Tools은 2.1.1 -version
설치 패키지 Microsoft.EntityFrameworkCore.SqlServer.Design
4 : 데이터베이스 컨텍스트 업데이트 클래스를 만듭니다
/// <summary>
/// 数据库创建和更新的上下文类
/// </summary>
public partial class MarketDbContext : DbContext
{
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
optionsBuilder.UseSqlServer("server=localhost;database=Market;uid=sa;pwd=123456;");
}
public virtual DbSet<AdminInfo> AdminInfo { get; set; }
}
5 : 프로젝트 웹 프로젝트 참조에 물리적 레이어를 추가하면 콘솔 Nuget에서 다음 명령을 입력
build001 마이그레이션 추가
생성 된 마이그레이션 파일
데이터베이스 갱신
다음과 같이 데이터베이스를 생성
6 : 추가 패킷 System.Linq.Dynamic.Core Nuget 동안 데이터 액세스 계층 스토리지베이스 클래스 및 인터페이스를 추가
/// <summary>
/// 仓储基类
/// </summary>
/// <typeparam name="T">实体类型</typeparam>
public abstract class RepositoryBase<T> : IRepository<T> where T : class
{
//定义数据访问上下文对象
protected readonly SyDbContext _dbContext;
/// <summary>
/// 通过构造函数注入得到数据上下文对象实例
/// </summary>
/// <param name="dbContext"></param>
public RepositoryBase(SyDbContext dbContext)
{
_dbContext = dbContext;
}
#region 同步
/// <summary>
/// 判断记录是否存在
/// </summary>
/// <param name="predicate">lambda表达式条件</param>
/// <returns></returns>
public bool IsExist(Expression<Func<T, bool>> predicate)
{
return _dbContext.Set<T>().Any(predicate);
}
/// <summary>
/// 新增实体
/// </summary>
/// <param name="entity">实体</param>
/// <param name="autoSave">是否立即执行保存</param>
/// <returns></returns>
public bool Add(T entity, bool autoSave = true)
{
int row = 0;
_dbContext.Set<T>().Add(entity);
if (autoSave)
row = Save();
return (row > 0);
}
/// <summary>
/// 批量添加
/// </summary>
/// <param name="entities">实体列表</param>
/// <param name="autoSave">是否立即执行保存</param>
/// <returns></returns>
public bool AddRange(IEnumerable<T> entities, bool autoSave = true)
{
int row = 0;
_dbContext.Set<T>().AddRange(entities);
if (autoSave)
row = Save();
return (row > 0);
}
/// <summary>
/// 更新实体
/// </summary>
/// <param name="entity">实体</param>
/// <param name="autoSave">是否立即执行保存</param>
public bool Update(T entity, bool autoSave = true)
{
int row = 0;
_dbContext.Update(entity);
if (autoSave)
row = Save();
return (row > 0);
}
/// <summary>
/// 更新实体部分属性
/// </summary>
/// <param name="entity">实体</param>
/// <param name="autoSave">是否立即执行保存</param>
/// <param name="updatedProperties">要更新的字段</param>
/// <returns></returns>
public bool Update(T entity, bool autoSave = true, params Expression<Func<T, object>>[] updatedProperties)
{
int row = 0;
//告诉EF Core开始跟踪实体的更改,
//因为调用DbContext.Attach方法后,EF Core会将实体的State值
//更改回EntityState.Unchanged,
_dbContext.Attach(entity);
if (updatedProperties.Any())
{
foreach (var property in updatedProperties)
{
//告诉EF Core实体的属性已经更改。将属性的IsModified设置为true后,
//也会将实体的State值更改为EntityState.Modified,
//这样就保证了下面SaveChanges的时候会将实体的属性值Update到数据库中。
_dbContext.Entry(entity).Property(property).IsModified = true;
}
}
if (autoSave)
row = Save();
return (row > 0);
}
/// <summary>
/// 更新实体部分属性,泛型方法
/// </summary>
/// <param name="entity">实体</param>
/// <param name="autoSave">是否立即执行保存</param>
/// <param name="updatedProperties">要更新的字段</param>
/// <returns></returns>
public bool Update<Entity>(Entity entity, bool autoSave = true, params Expression<Func<Entity, object>>[] updatedProperties) where Entity : class
{
int row = 0;
//告诉EF Core开始跟踪实体的更改,
//因为调用DbContext.Attach方法后,EF Core会将实体的State值
//更改回EntityState.Unchanged,
_dbContext.Attach(entity);
if (updatedProperties.Any())
{
foreach (var property in updatedProperties)
{
//告诉EF Core实体的属性已经更改。将属性的IsModified设置为true后,
//也会将实体的State值更改为EntityState.Modified,
//这样就保证了下面SaveChanges的时候会将实体的属性值Update到数据库中。
_dbContext.Entry(entity).Property(property).IsModified = true;
}
}
if (autoSave)
row = Save();
return (row > 0);
}
/// <summary>
/// 批量更新实体
/// </summary>
/// <param name="entities">实体列表</param>
/// <param name="autoSave">是否立即执行保存</param>
public bool UpdateRange(IEnumerable<T> entities, bool autoSave = true)
{
int row = 0;
_dbContext.UpdateRange(entities);
if (autoSave)
row = Save();
return (row > 0);
}
/// <summary>
/// 根据lambda表达式条件获取单个实体
/// </summary>
/// <param name="predicate">lambda表达式条件</param>
/// <returns></returns>
public T GetModel(Expression<Func<T, bool>> predicate)
{
return _dbContext.Set<T>().FirstOrDefault(predicate);
}
/// <summary>
/// 删除实体
/// </summary>
/// <param name="entity">要删除的实体</param>
/// <param name="autoSave">是否立即执行保存</param>
public bool Delete(T entity, bool autoSave = true)
{
int row = 0;
_dbContext.Set<T>().Remove(entity);
if (autoSave)
row = Save();
return (row > 0);
}
/// <summary>
/// 批量删除
/// </summary>
/// <param name="T">对象集合</param>
/// <returns></returns>
public bool Delete(IEnumerable<T> entities)
{
_dbContext.Set<T>().RemoveRange(entities);
int row = _dbContext.SaveChanges();
return (row > 0);
}
/// <summary>
/// 批量删除
/// </summary>
/// <param name="T">对象集合</param>
/// <param name="autoSave">是否立即执行保存</param>
/// <returns></returns>
public bool Delete(IEnumerable<T> entities, bool autoSave = true)
{
int row = 0;
_dbContext.Set<T>().RemoveRange(entities);
if (autoSave)
row = Save();
return (row > 0);
}
/// <summary>
/// 获取实体集合
/// </summary>
/// <returns></returns>
public virtual IQueryable<T> GetList()
{
return _dbContext.Set<T>().AsQueryable();
}
/// <summary>
/// 根据lambda表达式条件获取单个实体
/// </summary>
/// <param name="predicate">lambda表达式条件</param>
/// <returns></returns>
public virtual IQueryable<T> GetList(Expression<Func<T, bool>> predicate)
{
return _dbContext.Set<T>().Where(predicate);
}
/// <summary>
/// 根据lambda表达式条件获取实体集合
/// </summary>
/// <param name="top">前几条</param>
/// <param name="predicate">查询条件</param>
/// <param name="ordering">排序</param>
/// <param name="args">条件参数</param>
/// <returns></returns>
public virtual IQueryable<T> GetList(int top, string predicate, string ordering, params object[] args)
{
var result = _dbContext.Set<T>().AsQueryable();
if (!string.IsNullOrWhiteSpace(predicate))
result = result.Where(predicate, args);
if (!string.IsNullOrWhiteSpace(ordering))
result = result.OrderBy(ordering);
if (top > 0)
{
result = result.Take(top);
}
return result;
}
/// <summary>
/// 分页查询,返回实体对象
/// </summary>
/// <param name="pageIndex">当前页</param>
/// <param name="pageSize">页大小</param>
/// <param name="predicate">条件</param>
/// <param name="ordering">排序</param>
/// <param name="args">条件参数</param>
/// <returns></returns>
public virtual IQueryable<T> GetPagedList(int pageIndex, int pageSize, string predicate, string ordering, params object[] args)
{
var result = (from p in _dbContext.Set<T>()
select p).AsQueryable();
if (!string.IsNullOrWhiteSpace(predicate))
result = result.Where(predicate, args);
if (!string.IsNullOrWhiteSpace(ordering))
result = result.OrderBy(ordering);
return result.Skip((pageIndex - 1) * pageSize).Take(pageSize);
}
/// <summary>
/// 获取记录总数
/// </summary>
/// <param name="predicate">查询条件</param>
/// <param name="args">条件参数</param>
/// <returns></returns>
public virtual int GetRecordCount(string predicate, params object[] args)
{
if (string.IsNullOrWhiteSpace(predicate))
{
return _dbContext.Set<T>().Count();
}
else
{
return _dbContext.Set<T>().Where(predicate, args).Count();
}
}
/// <summary>
/// 事务性保存
/// </summary>
public int Save()
{
int result = _dbContext.SaveChanges();
return result;
}
#endregion
}
/// <summary>
/// 定义泛型仓储接口
/// </summary>
/// <typeparam name="TEntity">实体类型</typeparam>
public interface IRepository<T> where T : class
{
#region 同步
/// <summary>
/// 判断记录是否存在
/// </summary>
/// <param name="predicate">lambda表达式条件</param>
/// <returns></returns>
bool IsExist(Expression<Func<T, bool>> predicate);
/// <summary>
/// 新增实体
/// </summary>
/// <param name="entity">实体</param>
/// <param name="autoSave">是否立即执行保存</param>
/// <returns></returns>
bool Add(T entity, bool autoSave = true);
/// <summary>
/// 批量添加
/// </summary>
/// <param name="entities">实体列表</param>
/// <param name="autoSave">是否立即执行保存</param>
/// <returns></returns>
bool AddRange(IEnumerable<T> entities, bool autoSave = true);
/// <summary>
/// 更新实体
/// </summary>
/// <param name="entity">实体</param>
/// <param name="autoSave">是否立即执行保存</param>
bool Update(T entity, bool autoSave = true);
/// <summary>
/// 更新部分属性
/// </summary>
/// <param name="entity">实体</param>
/// <param name="autoSave">是否立即执行保存</param>
/// <param name="updatedProperties">要更新的字段</param>
/// <returns></returns>
bool Update(T entity, bool autoSave = true, params Expression<Func<T, object>>[] updatedProperties);
/// <summary>
/// 更新实体部分属性,泛型方法
/// </summary>
/// <param name="entity">实体</param>
/// <param name="autoSave">是否立即执行保存</param>
/// <param name="updatedProperties">要更新的字段</param>
/// <returns></returns>
bool Update<Entity>(Entity entity, bool autoSave = true, params Expression<Func<Entity, object>>[] updatedProperties) where Entity : class;
/// <summary>
/// 批量更新实体
/// </summary>
/// <param name="entities">实体列表</param>
/// <param name="autoSave">是否立即执行保存</param>
bool UpdateRange(IEnumerable<T> entities, bool autoSave = true);
/// <summary>
/// 删除实体
/// </summary>
/// <param name="entity">要删除的实体</param>
/// <param name="autoSave">是否立即执行保存</param>
bool Delete(T entity, bool autoSave = true);
/// <summary>
/// 批量删除
/// </summary>
/// <param name="T">对象集合</param>
/// <returns></returns>
bool Delete(IEnumerable<T> entities);
/// <summary>
/// 批量删除
/// </summary>
/// <param name="T">对象集合</param>
/// <param name="autoSave">是否立即执行保存</param>
/// <returns></returns>
bool Delete(IEnumerable<T> entities, bool autoSave = true);
/// <summary>
/// 获取实体集合
/// </summary>
/// <returns></returns>
IQueryable<T> GetList();
/// <summary>
/// 根据lambda表达式条件获取实体集合
/// </summary>
/// <param name="top">前几条</param>
/// <param name="predicate">查询条件</param>
/// <param name="ordering">排序</param>
/// <param name="args">条件参数</param>
/// <returns></returns>
IQueryable<T> GetList(int top, string predicate, string ordering, params object[] args);
/// <summary>
/// 根据lambda表达式条件获取实体集合
/// </summary>
/// <param name="predicate">lambda表达式条件</param>
/// <returns></returns>
IQueryable<T> GetList(Expression<Func<T, bool>> predicat);
/// <summary>
/// 根据lambda表达式条件获取单个实体
/// </summary>
/// <param name="predicate">lambda表达式条件</param>
/// <returns></returns>
T GetModel(Expression<Func<T, bool>> predicate);
/// <summary>
/// 分页查询
/// </summary>
/// <param name="pageIndex">当前页</param>
/// <param name="pageSize">页大小</param>
/// <param name="predicate">条件</param>
/// <param name="ordering">排序</param>
/// <param name="args">条件参数</param>
/// <returns></returns>
IQueryable<T> GetPagedList(int pageIndex, int pageSize, string predicate, string ordering, params object[] args);
/// <summary>
/// 获取记录总数
/// </summary>
/// <param name="predicate">查询条件</param>
/// <param name="args">条件参数</param>
/// <returns></returns>
int GetRecordCount(string predicate, params object[] args);
/// <summary>
/// 保存
/// </summary>
int Save();
#endregion
}
7 : 데이터 액세스 계층에서 문맥 기반 데이터베이스 액세스를 추가
/// <summary>
/// 数据库上下文访问类
/// </summary>
public class SyDbContext:DbContext
{
public virtual DbSet<AdminInfo> AdminInfo { get; set; }
/// <summary>
/// 构造函数
/// </summary>
/// <param name="options"></param>
public SyDbContext(DbContextOptions<SyDbContext> options) : base(options)
{
}
}
8 : 비즈니스 계층은 AdminInfoService, IAdminInfoService를 추가
9 : appsetting.json 한층 웹 연결 문자열
"ConnectionStrings": {
"ConnectionString을": "서버 = 로컬 호스트, 데이터베이스 = 시장; UID = sa를; PWD = 123456;"
}
10 : 수정 CreateWebHostBuilder 방법 program.cs
public static IWebHostBuilder CreateWebHostBuilder(string[] args)
{
var configuration = new ConfigurationBuilder()
.SetBasePath(Environment.CurrentDirectory)
.AddJsonFile("appsettings.json")//读取配置文件,获取启动的端口号
.Build();
return WebHost.CreateDefaultBuilder(args)
.UseConfiguration(configuration)
.UseStartup<Startup>();
}