CSharp-Single-EFCore/Bunny.Common/Context/Database/EFCoreContext.cs

140 lines
4.8 KiB
C#
Raw Normal View History

using Bunny.Dao.Entity;
using Bunny.Dao.Entity.System;
using Bunny.Dao.Entity.System.Dept;
using Bunny.Dao.Entity.System.Menu;
using Bunny.Dao.Entity.System.User;
using log4net;
using Microsoft.EntityFrameworkCore;
namespace Bunny.Common.Context.Database;
/// <summary>
/// EfCore 连接内容
/// dotnet tool install --global dotnet-ef
/// dotnet add package Microsoft.EntityFrameworkCore.Design
/// dotnet ef migrations add InitialCreate
/// dotnet ef database update
/// </summary>
public class EfCoreContext : DbContext
{
private static readonly ILog Log = LogManager.GetLogger(typeof(EfCoreContext));
public EfCoreContext()
{
var dataBaseConnection = AppSettings.GetAppConfig<string>("DataBase:DataBaseConnection");
// const string dataBaseConnection =
// "192.168.3.98;Initial Catalog=BunnyDemo;TrustServerCertificate=True;Persist Security Info=True;Users ID=sa;Password=abc1234.";
DbPath = $"Data Source={dataBaseConnection}";
}
// 连接路径
private string DbPath { get; }
public DbSet<Icons> Icons { get; set; }
public DbSet<Dept> Dept { get; set; }
public DbSet<DeptUsers> DeptUsers { get; set; }
public DbSet<Users> Users { get; set; }
public DbSet<Roles> Roles { get; set; }
public DbSet<Permissions> Permissions { get; set; }
public DbSet<UserRoles> UserRoles { get; set; }
public DbSet<UserPermissions> UserPermissions { get; set; }
public DbSet<Menus> Menus { get; set; }
public DbSet<MenuRoles> MenuRoles { get; set; }
public DbSet<MenuPermissions> MenuPermissions { get; set; }
/// <summary>
/// 配置数据库上下文选项,指定数据库连接字符串
/// </summary>
protected override void OnConfiguring(DbContextOptionsBuilder options)
{
options.UseSqlServer(DbPath);
}
/// <summary>
/// 在创建模型时为所有继承自BaseEntity的实体类型添加软删除查询过滤器
/// </summary>
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
// 为每个表指定 blogging 架构
modelBuilder.HasDefaultSchema("blogging");
// 根据基础类型创建数据库表
foreach (var entityType in modelBuilder.Model.GetEntityTypes())
if (typeof(BaseEntity).IsAssignableFrom(entityType.ClrType))
entityType.AddSoftDeleteQueryFilter();
base.OnModelCreating(modelBuilder);
}
/// <summary>
/// 重写SaveChanges方法在保存更改之前设置系统字段
/// </summary>
public override int SaveChanges()
{
SetSystemField();
return base.SaveChanges();
}
/// <summary>
/// 重写SaveChanges方法在保存更改之前设置系统字段
/// </summary>
public override int SaveChanges(bool acceptAllChangesOnSuccess)
{
SetSystemField();
return base.SaveChanges(acceptAllChangesOnSuccess);
}
/// <summary>
/// 异步保存更改,设置系统字段
/// </summary>
public override Task<int> SaveChangesAsync(CancellationToken cancellationToken = new())
{
SetSystemField();
return base.SaveChangesAsync(cancellationToken);
}
/// <summary>
/// 异步保存更改,设置系统字段
/// </summary>
public override Task<int> SaveChangesAsync(bool acceptAllChangesOnSuccess,
CancellationToken cancellationToken = new())
{
SetSystemField();
return base.SaveChangesAsync(acceptAllChangesOnSuccess, cancellationToken);
}
/// <summary>
/// 系统字段赋值
/// </summary>
private void SetSystemField()
{
foreach (var item in ChangeTracker.Entries())
if (item.Entity is BaseEntity entity)
{
var userId = BaseContext.GetUserId();
switch (item.State)
{
// 添加操作
case EntityState.Added:
{
if (entity.Id == Guid.Empty) entity.Id = Guid.NewGuid();
entity.CreateTime = DateTime.Now;
entity.UpdateTime = DateTime.Now;
entity.Version = DateTime.Now;
// 判断用户Id是否为空
if (userId != null && userId != 0)
{
entity.CreateUserId = userId.Value;
entity.UpdateUserId = userId.Value;
}
break;
}
// 修改操作
case EntityState.Modified:
entity.UpdateTime = DateTime.Now;
if (userId != null) entity.UpdateUserId = userId.Value;
break;
}
}
}
}