對于模塊的實體屬性蜈漓,都是在模塊中定義好的蹲堂,無法更改模塊內部代碼黍翎。我們可以通過擴展實體來向模塊實體增加屬性。
Extra Properties
Extra properties是一種存儲實體的一些額外數據但不用更改實體的方式. 實體應該實現(xiàn) IHasExtraProperties
接口. 所有預構建模塊定義的聚合根實體都實現(xiàn)了 IHasExtraProperties
接口,所以你可以在這些實體中存儲額外的屬性.
示例:
//SET AN EXTRA PROPERTY
var user = await _identityUserRepository.GetAsync(userId);
user.SetProperty("Title", "My custom title value!");
await _identityUserRepository.UpdateAsync(user);
//GET AN EXTRA PROPERTY
var user = await _identityUserRepository.GetAsync(userId);
return user.GetProperty<string>("Title");
這種方法開箱即用并且非常簡單,你可以使用不同的屬性名稱(如這里的Title)在同一時間存儲多個屬性.
對于EF Core額外的屬性被格式化成單個 JSON 字符值串存儲在數據庫中. 對于MongoDB它們做為單獨的字段存儲.
實體擴展 (EF Core)
如上所述,實體所有的額外屬性都作為單個JSON對象存儲在數據庫表中. 它不適用復雜的場景,特別是在你需要的時候.
- 使用額外屬性創(chuàng)建索引和外鍵.
- 使用額外屬性編寫SQL或LINQ(例如根據屬性值搜索).
- 創(chuàng)建你自己的實體映射到相同的表,但在實體中定義一個額外屬性做為 常規(guī)屬性
為了解決上面的問題,用于EF Core的ABP框架實體擴展系統(tǒng)允許你使用上面定義相同的額外屬性API,但將所需的屬性存儲在單獨的數據庫表字段中.
假設你想要添加 SocialSecurityNumber
到身份模塊的 IdentityUser
實體. 你可以使用 ObjectExtensionManager
類:
擴展實體腻要,在項目Project.EntityFrameworkCore
的ProjectEfCoreEntityExtensionMappings
文件中添加如下代碼
ObjectExtensionManager.Instance
.MapEfCoreProperty<IdentityUser, string>(
"SocialSecurityNumber",
(entityBuilder, propertyBuilder) =>
{
propertyBuilder.HasMaxLength(32);
}
);
擴展DTO复罐,在項目Project.Application.Contracts
的ProjectDtoExtensions
文件中添加如下代碼
ObjectExtensionManager.Instance
.AddOrUpdateProperty<string>(
new[] {
typeof(IdentityUserDto),
typeof(IdentityUserCreateDto),
typeof(IdentityUserUpdateDto),
typeof(ProfileDto),
typeof(UpdateProfileDto)
}, "SocialSecurityNumber"
)
.AddOrUpdateProperty<Guid>(
new[] {
typeof(IdentityUserDto),
typeof(IdentityUserCreateDto),
typeof(IdentityUserUpdateDto),
typeof(ProfileDto),
typeof(UpdateProfileDto)
}, "IdentityInfo"
);
然后就是添加遷移更新數據庫了:
Add-Migration Added_AppUser_Properties
運行 Update-Database
或著運行DbMigrator項目來更新