前言:
项目开发过程中难免会涉及到一些业务相关的基础数据,我们称之为种子数据,主要为了方便测试功能或者展示效果;
常规做法是手动到数据库表创建数据,但是随着表结构更改或者数据清空后,又要重新录入基础数据,很是麻烦;
采用CodeFirst 通过建模领域对象生成实体表结构的方式,为了便于种子数据的存储和管理,一个好的解决方案显得极为重要,Abp Vnext 项目模板中xxx.ProjectName.DbMigrator 项目就是用于种子数据初始化到数据库的控制台程序;
具体步骤:
1、 在xxx.Domain领域服务中的 data目录下 新建 DefaultDataSeederContributor.cs 用于存放种子数据:
![](https://img.laitimes.com/img/9ZDMuAjOiMmIsIjOiQnIsIyZuBnL4IzMxATN1EjM4AjMwEjMwIzLc52YucWbp5GZzNmLn9Gbi1yZtl2Lc9CX6MHc0RHaiojIsJye.png)
public class DefaultDataSeederContributor : IDataSeedContributor, ITransientDependency
{
public readonly IRepository<Resource,string> _resources;
public DefaultDataSeederContributor(IRepository<Resource,string> resources)
{
_resources = resources;
}
public async Task SeedAsync(DataSeedContext context)
{
//1、初始化静态资源Resource数据
await CreateResourceDataAsync();
//2、初始化其他数据库表数据******
}
/// <summary>
/// Resource表静态资源初始化
/// </summary>
/// <returns></returns>
private async Task CreateResourceDataAsync()
{
//1、清空所有数据
//await _resources.DeleteAsync(p => p.Id == "CruiseType"); //删除无效 不知为何
//2、提取种子数据
var tmpDataLst = GetResourceData();
//3、循环插入数据
foreach (var item in tmpDataLst)
{
var tmpEntity = await _resources.FirstOrDefaultAsync(p => p.Id == item.Id);
if (tmpEntity != null)
{
//数据当前数据存在删除当前记录DeleteAsync(tmpEntity);
//如果 继承了软删除 ISoftDelete 则需要调用 强制删除:HardDeleteAsync(tmpEntity) ;
await _resources.HardDeleteAsync(tmpEntity);
}
await _resources.InsertAsync(item);
}
}
/// <summary>
/// Resource静态资源配置
/// </summary>
/// <returns></returns>
private List<Resource> GetResourceData()
{
List<Resource> tmpDataLst = new List<Resource>();
//1、任务资源类型:
tmpDataLst.AddRange(new List<Resource>{
new Resource() {Id="CruiseType",Name="巡检类型"},
new Resource() {Id="CruiseType_Preset",Name="预置巡航"},
new Resource() {Id="CruiseType_Area",Name="区域巡航"}
});
return tmpDataLst;
}
}
2、xxx.ProjectName.DbMigrator 项目 xxxModule.cs 模块类中添加种子数据类:
public class GasMonitoringDbMigratorModule : AbpModule
{
public override void ConfigureServices(ServiceConfigurationContext context)
{
Configure<AbpBackgroundJobOptions>(options => options.IsJobExecutionEnabled = false);
// Remove the contributor for migrator module
context.Services.RemoveAll(t => t.ImplementationType == typeof(IDataSeedContributor));
// Add custom data seed contributor
context.Services.AddTransient<IDataSeedContributor, DefaultDataSeederContributor>();
}
}
3、启动xxx.ProjectName.DbMigrator项目,即可将数据初始化到数据库;
4、或者控制台管理程序 cd 到DbMigrator项目 调用 dotnet run 命令
总结:
这样种子数据就跟着项目走了,便于管理更改和重复使用;