前面两节使用ABP CLI创建了模块开发的基础框架,现在开始创建一个简单的应用,完成一个单个实体的CRUD。首先在.Domain项目中增加一个实体类:
using System;
using System.Collections.Generic;
using System.Text;
using Volo.Abp.Domain.Entities.Auditing;
namespace ZL.MyFirstModule
{
public class Poet : AuditedAggregateRoot<Guid>
{
public string Name { get; set; }
public string Description { get; set; }
}
}
这个类从ABP框架中的AuditedAggregateRoot派生,使用Guid类型作为关键字。
然后在.EntityFrameworkCore项目的DbContext中增加相应的DbSet:
using Microsoft.EntityFrameworkCore;
using Volo.Abp.Data;
using Volo.Abp.EntityFrameworkCore;
namespace ZL.MyFirstModule.EntityFrameworkCore
{
[ConnectionStringName(MyFirstModuleDbProperties.ConnectionStringName)]
public class MyFirstModuleDbContext : AbpDbContext<MyFirstModuleDbContext>, IMyFirstModuleDbContext
{
/* Add DbSet for each Aggregate Root here. Example:
* public DbSet<Question> Questions { get; set; }
*/
public DbSet<Poet> Poets { get; set; }
public MyFirstModuleDbContext(DbContextOptions<MyFirstModuleDbContext> options)
: base(options)
{
}
protected override void OnModelCreating(ModelBuilder builder)
{
base.OnModelCreating(builder);
builder.ConfigureMyFirstModule();
}
}
}
接下来,在DbContextModelCreatingExtensions中增加数据库映射:
builder.Entity<Poet>(b =>
{
b.ToTable(options.TablePrefix + "Poets",
options.Schema);
b.ConfigureByConvention(); //auto configure for the base class props
b.Property(x => x.Name).IsRequired().HasMaxLength(128);
});
到这里,实体和在关系数据库中的映射就创建完成了,在程序包管理器中运行Add-Migration "Created_Poet_Entity",默认项目选择.Web.Unified,创建相关的迁移,然后执行Update-Database,更新数据库:

我们打开生成的数据库,看一下新生成的表:

可以看到,除了我们实体中的两个属性外,还创建了很多用于审计的字段,这些都是ABP框架自动完成的。
还需要修改模板生成的EntityFrameworkCoreModule,增加缺省Resposistories:
using Microsoft.Extensions.DependencyInjection;
using Volo.Abp.EntityFrameworkCore;
using Volo.Abp.Modularity;
namespace ZL.MyFirstModule.EntityFrameworkCore
{
[DependsOn(
typeof(MyFirstModuleDomainModule),
typeof(AbpEntityFrameworkCoreModule)
)]
public class MyFirstModuleEntityFrameworkCoreModule : AbpModule
{
public override void ConfigureServices(ServiceConfigurationContext context)
{
context.Services.AddAbpDbContext<MyFirstModuleDbContext>(options =>
{
/* Add custom repositories here. Example:
* options.AddRepository<Question, EfCoreQuestionRepository>();
*/
options.AddDefaultRepositories(includeAllEntities: true);
});
}
}
}
接下来,可以创建应用层了。
网友评论