愿你出走半生,归来仍是少年!
1.DbContext
创建自己的DbContext并继承Abp的对应类和接口,实现基础的身份验证模块的数据库支持(基于Microsoft Identity 库 ),并配置PostGresql的Postgis插件检查等。
[ReplaceDbContext(typeof(IIdentityDbContext))]
[ReplaceDbContext(typeof(ITenantManagementDbContext))]
[ConnectionStringName("Default")]
public class DefaultDbContext :
AbpDbContext<DefaultDbContext> ,
IIdentityDbContext,
ITenantManagementDbContext
{
#region 用户识别
//用户管理
public DbSet<IdentityUser> Users { get; set; }
public DbSet<IdentityRole> Roles { get; set; }
public DbSet<IdentityClaimType> ClaimTypes { get; set; }
public DbSet<OrganizationUnit> OrganizationUnits { get; set; }
public DbSet<IdentitySecurityLog> SecurityLogs { get; set; }
public DbSet<IdentityLinkUser> LinkUsers { get; set; }
// 租户管理
public DbSet<Tenant> Tenants { get; set; }
public DbSet<TenantConnectionString> TenantConnectionStrings { get; set; }
#endregion
/// <summary>
/// 默认的书户口连接
/// </summary>
/// <param name="options"></param>
public DefaultDbContext(DbContextOptions<DefaultDbContext> options ) : base(options)
{
}
protected override void OnModelCreating(ModelBuilder builder)
{
base.OnModelCreating(builder);
builder.HasPostgresExtension("postgis");//确认PG插件
/* Include modules to your migration db context */
builder.ConfigurePermissionManagement();//AbpPermissionGrants表
builder.ConfigureSettingManagement();
builder.ConfigureBackgroundJobs();
builder.ConfigureAuditLogging();
builder.ConfigureIdentity();
//builder.ConfigureIdentityServer();
builder.ConfigureFeatureManagement();
builder.ConfigureTenantManagement();
/* Configure your own tables/entities inside here */
//SeedHelper seedHelper = new SeedHelper(_guidGenerator);
//seedHelper.Seed(builder);
}
}
2.种子数据
创建自己的种子数据注入类,继承IDataSeedContributor接口,并实现数据创建。
public class DefaultDbSeeder : IDataSeedContributor, ITransientDependency
{
private readonly IRepository<IdentityUser, Guid> _userRepository;
private readonly IGuidGenerator _guidGenerator;
private readonly IdentityUserManager _userManager;
public DefaultDbSeeder(
IGuidGenerator guidGenerator,
IRepository<IdentityUser, Guid> userRepository,
IdentityUserManager userManager )
{
_guidGenerator = guidGenerator;
_userRepository = userRepository;
_userManager = userManager;
}
public async Task SeedAsync(DataSeedContext context)
{
if (await _userRepository.GetCountAsync() <= 1)
{
var userSpe = new IdentityUser(_guidGenerator.Create(), "spe", "25@qq.com");
userSpe.SetPhoneNumber("", true);
userSpe.Name = "";
userSpe = await _userRepository.InsertAsync(
userSpe,
autoSave: true
);
await _userManager.AddPasswordAsync(userSpe, "1q2w3E*");
await _userManager.SetRolesAsync(userSpe, new List<string>() { "admin" });
var userHp = new IdentityUser(_guidGenerator.Create(), "hp", "@qq.com");
userHp.SetPhoneNumber("", true);
userHp.Name = "侯";
userHp = await _userRepository.InsertAsync(
userHp,
autoSave: true
);
await _userManager.AddPasswordAsync(userHp, "1q2w3E*");
await _userManager.SetRolesAsync(userHp, new List<string>() { "admin" });
}
}
}
3.实体字段扩展
创建EfCoreEntityExtensionMappings静态类,配置实体的字段扩展。
public static class EfCoreEntityExtensionMappings
{
private static readonly OneTimeRunner OneTimeRunner = new OneTimeRunner();
public static void Configure()
{
GlobalFeatureConfigurator.Configure();
ExtensionConfigurator.Configure();
OneTimeRunner.Run(() =>
{
/* You can configure extra properties for the
* entities defined in the modules used by your application.
*
* This class can be used to map these extra properties to table fields in the database.
*
* USE THIS CLASS ONLY TO CONFIGURE EF CORE RELATED MAPPING.
* USE LandManagerModuleExtensionConfigurator CLASS (in the Domain.Shared project)
* FOR A HIGH LEVEL API TO DEFINE EXTRA PROPERTIES TO ENTITIES OF THE USED MODULES
*
* Example: Map a property to a table field:
ObjectExtensionManager.Instance
.MapEfCoreProperty<IdentityUser, string>(
"MyProperty",
(entityBuilder, propertyBuilder) =>
{
propertyBuilder.HasMaxLength(128);
}
);
* See the documentation for more:
* https://docs.abp.io/en/abp/latest/Customizing-Application-Modules-Extending-Entities
*/
//Role添加NickName作为中文名称存储
ObjectExtensionManager.Instance
.MapEfCoreProperty<IdentityRole, string>(
"NickName",
(entityBuilder, propertyBuilder) =>
{
propertyBuilder.HasMaxLength(32);
}
);
});
}
}
4.模块化文件
创建模块化文件,并针对数据库、默认仓储、种子数据进行配置。
/// <summary>
/// EF模块
/// </summary>
[DependsOn(
typeof(AbpEntityFrameworkCorePostgreSqlModule),
typeof(AbpAuditLoggingEntityFrameworkCoreModule),
typeof(AbpIdentityEntityFrameworkCoreModule),
typeof(AbpPermissionManagementEntityFrameworkCoreModule),
typeof(AbpSettingManagementEntityFrameworkCoreModule),
typeof(AbpBackgroundJobsEntityFrameworkCoreModule),
typeof(AbpTenantManagementEntityFrameworkCoreModule),
typeof(AbpFeatureManagementEntityFrameworkCoreModule),
typeof(LandManagerDomainModule)
)]
public class LandManagerEntityFrameworkCoreModule:AbpModule
{
public LandManagerEntityFrameworkCoreModule() { }
public override void PreConfigureServices(ServiceConfigurationContext context)
{
//解决PG DateTime with Kind=Local 问题
AppContext.SetSwitch("Npgsql.EnableLegacyTimestampBehavior", true);
EfCoreEntityExtensionMappings.Configure();
}
public override void ConfigureServices(ServiceConfigurationContext context)
{
context.Services.AddAbpDbContext<DefaultDbContext>(options =>
{
//面向实体和聚合根 提供默认仓储
options.AddDefaultRepositories(includeAllEntities: true);
});
//PGSQL
Configure<AbpDbContextOptions>(options =>
{
options.UseNpgsql(o=>o.UseNetTopologySuite());//添加空间数据库支持
});
}
public override void OnPostApplicationInitialization(ApplicationInitializationContext context)
{
//种子数据写入
context.GetApplicationBuilder().ApplicationServices.GetRequiredService<IDataSeeder>().SeedAsync();
}
}