Abp vNext 扩展User表
背景
使用vNext搭建了项目,因项目需要给用户配置头像,但abp Zero模块中的User实体是不包含头像信息的,于是有了这个需求:扩展内置实体。为User表添加头像等信息。
步骤
1、新建MyUser类
该类用来定义新增的字段,不需要继承任何父类,如下所示:
public class MyUser
{
#region const
public const int MaxAvatarLength = 366;
#endregion
/// <summary>
/// 头像
/// </summary>
public string Avatar { get; set; }
}
2、添加MyAppEfCoreEntityExtensionMappings类,
类名可以随意,但是按照惯例,一般以“项目名”+EfCoreEntityExtensionMappings命名。该类主要用来配置为IdentityUser新增字段,代码如下:
public static class MyAppEfCoreEntityExtensionMappings
{
private static readonly OneTimeRunner OneTimeRunner = new OneTimeRunner();
public static void Configure()
{
MyAppModulePropertyConfigurator.Configure();
OneTimeRunner.Run(() =>
{
ObjectExtensionManager.Instance
.MapEfCoreProperty<IdentityUser, string>(
nameof(User.Avatar),
(entityBuilder, propertyBuilder) =>
{
propertyBuilder.HasMaxLength(User.MaxAvatarLength);
}
);
});
}
}
3、配置MyAppEntityFrameworkCoreModule模块中的PreConfigureServices
将上一步配置的内容,在模块中加载,代码如下:
public override void PreConfigureServices(ServiceConfigurationContext context)
{
MyAppEfCoreEntityExtensionMappings.Configure();
...
base.PreConfigureServices(context);
}
4、配置DbContextFactory类中的CreateDbContext
同上一步,在DbContextFactory中进行同样配置,一些情况下我们需要通过DbContextFactory来获取DbContext,如不配置此项,将会导致获取的DbContext中内容不一致。
public MyAppDbContext CreateDbContext(string[] args)
{
MyAppEfCoreEntityExtensionMappings.Configure();
return new MyAppDbContext(builder.Options);
}
5、配置应用层Dto扩展
因头像Avatar信息是我们追加给IdentityUser的,Abp Zero中内置的User相关Dto是没有此项内容的,我们需要对这些Dto做一些添加属性的操作。在Application.Contracts层,新建一个名为MyAppDtoExtensions的类,当然类名称随意。
public static class MyAppDtoExtensions
{
private static readonly OneTimeRunner OneTimeRunner = new OneTimeRunner();
public static void Configure()
{
OneTimeRunner.Run(() =>
{
ObjectExtensionManager.Instance
.AddOrUpdateProperty<string>(
new[]
{
typeof(IdentityUserDto),
typeof(IdentityUserCreateDto),
typeof(IdentityUserUpdateDto),
typeof(ProfileDto),
typeof(UpdateProfileDto)
},
"Avatar"
);
});
}
}
6、在模块类ApplicationContractsModule中进行配置
为了是上一步配置生效,还需要在MyAppApplicationContractsModule中进行如下配置:
public override void PreConfigureServices(ServiceConfigurationContext context)
{
MyAppDtoExtensions.Configure();
}
自此,所有操作均已完成,可以重新生成迁移,更新数据库了。这里只演示了在User实体中添加头像,如需在其他内置的实体中添加字段,步骤一样。
第六步我最新版本的怎么跟你这个不一样?我把服务配置过来后整个PreConfigureServices方法是不支持直接配置MyAppDtoExtensions类的。