Entity Management
Files Referenced in this Document
- IMyEntityNameAppService.cs
- MyEntityNameAppService.cs
- MyEntityNameAutoMapperProfile.cs
- MyEntityName.cs
- IMyEntityNameRepository.cs
Table of Contents
- Introduction
- CRUD Operation Implementation Mechanism
- DTO and Entity Mapping Mechanism
- Aggregate Root Lifecycle and Audit Field Management
- Soft Delete Processing Mechanism
- Pagination Query Method Comparison
- Permission Control and Data Validation
- API Call Examples
Introduction
This document deeply analyzes the implementation mechanism of CRUD (Create, Read, Update, Delete) operations for the MyEntityName entity. Focusing on the IMyEntityNameAppService interface and its concrete implementation class MyEntityNameAppService, it elaborates on business logic flows, object mapping, lifecycle management, audit field population, soft delete strategies, pagination query differences, and security validation mechanisms.
CRUD Operation Implementation Mechanism
MyEntityNameAppService implements the IMyEntityNameAppService interface, inheriting from the ABP framework's ICrudAppService, providing standard CRUD functions, and extending advanced functions such as batch operations, sort adjustment, and import/export.
- Create (CreateAsync): Receives
MyEntityNameCreateDto, verifies name uniqueness, generates a new entity, and inserts it into the database. - Read (GetAsync / GetListAsync): Gets a single entity by ID or queries a list by pagination conditions.
- Update (UpdateAsync): Loads an existing entity, applies changes from DTO, and executes the update.
- Delete (DeleteAsync / DeleteManyAsync): Supports single or multiple ID deletion, relying on the repository to implement soft delete.
- Sort Adjustment (AdjustSortAsync): Recalculates the sort values of all records to ensure the target item is at the specified position.
- Clone (CloneAsync): Copies the entity with the specified ID, automatically handling name conflicts and incrementing sort order.
- Import/Export (ImportAsync / ExportAsync): Supports batch import and export of data in Excel format, including row-level error feedback.
Section sources
DTO and Entity Mapping Mechanism
The system uses AutoMapper to convert between DTOs and domain entities. MyEntityNameAutoMapperProfile defines the mapping rules from MyEntityName to MyEntityNameDto.
Key configuration is as follows:
CreateMap<MyEntityName, MyEntityNameDto>(MemberList.None).MapExtraProperties(MappingPropertyDefinitionChecks.None);
MemberList.Nonemeans target members are not validated, only properties existing in the source are mapped.MapExtraPropertiesenables the ABP extended property mapping mechanism, allowing dynamic fields to be passed between DTO and entity.
This configuration ensures that entity properties are correctly mapped to DTOs while retaining additional extended properties (such as custom fields in JSON format), meeting flexible data structure requirements.
Section sources
Aggregate Root Lifecycle and Audit Field Management
The MyEntityName class inherits from FullAuditedAggregateRoot<Guid>, which is a fully audited aggregate root base class provided by the ABP framework, automatically managing the following audit fields:
| Audit Field | Type | Description |
|---|---|---|
| CreationTime | DateTime | Creation time, automatically populated by the framework |
| CreatorId | Guid? | Creator user ID, automatically recorded |
| LastModificationTime | DateTime? | Last modification time |
| LastModifierId | Guid? | Last modifier user ID |
| IsDeleted | bool | Soft delete flag |
| DeleterId | Guid? | Deleter user ID |
| DeletionTime | DateTime? | Deletion time |
These fields are automatically maintained by the ABP framework during entity creation, update, and deletion, requiring no manual coding. For example, when InsertAsync is called, CreationTime and CreatorId are automatically set to the current time and current user.
In addition, the constructor of MyEntityName uses methods like Check.NotNullOrWhiteSpace for parameter validation, ensuring the entity meets business constraints upon creation.
Section sources
Soft Delete Processing Mechanism
The system adopts a soft delete pattern. FullAuditedAggregateRoot<Guid> inherited by MyEntityName already implements the ISoftDelete interface. This means calling DeleteAsync does not physically delete the record from the database, but sets the IsDeleted field to true and records deletion-related information.
Advantages of this mechanism include:
- Data recoverability, avoiding accidental deletion
- Preserving historical data integrity
- Supporting audit trails
During queries, the ABP repository automatically filters out deleted records (i.e., IsDeleted == true) by default. If deleted data needs to be included, the includeDetails: true parameter can be explicitly specified during the query.
Section sources
Pagination Query Method Comparison
MyEntityNameAppService provides two pagination query methods:
GetAsync vs GetListAsync
| Method | Purpose | Return Type | Paged | Typical Scenario |
|---|---|---|---|---|
GetAsync(Guid id) | Get single entity | MyEntityNameDto | No | Load details for edit page |
GetListAsync(GetMyEntityNamesInput input) | Query entity list | PagedResultDto<MyEntityNameDto> | Yes | List page display |
GetListAsync Internal Flow
Diagram sources
GetListAsync uses MyEntityNameSpecification for conditional filtering, combined with filter and specification parameters to implement complex query logic, supporting scenarios like fuzzy matching by name.
Section sources
Permission Control and Data Validation
Permission Control
Although the current code does not directly show the [Authorize] attribute, according to ABP architectural conventions, application service methods are typically protected by declarative permissions. Permission definitions should be configured in CMSPluginMyPluginNameFeatures.cs or related permission providers to ensure only authorized users can perform CRUD operations.
Data Validation
The system adopts a multi-layer validation mechanism:
- DTO Level Validation: Pre-validation in the service layer via static methods like
Check.NotNull,Check.NotNullOrWhiteSpace. - Entity Level Validation: Re-validate key field lengths and non-nullability in
MyEntityNameconstructor andUpdatemethod. - Custom Business Rules: Such as
NameExistAsyncchecking name uniqueness to prevent duplicate submissions.
For example, CheckCreateOrUpdateDtoAsync is called during creation for unified validation:
Check.NotNullOrWhiteSpace(input.Code, "Code", MyEntityNameConsts.MaxCodeLength);
Check.NotNullOrWhiteSpace(input.Name, "Name", MyEntityNameConsts.MaxNameLength);
All validation failures throw UserFriendlyException, which the frontend can capture and display as friendly prompts to the user.
Section sources
API Call Examples
The following are typical API call scenarios (based on RESTful style):
Create Entity
POST /api/app/my-entity-name
Content-Type: application/json
{
"code": "ENT001",
"name": "Example Entity",
"remark": "This is a test entity"
}
Query Paged List
GET /api/app/my-entity-name?Filter=Example&Sorting=Name&MaxResultCount=10&SkipCount=0
Update Entity
PUT /api/app/my-entity-name/7d8e5d1a-1b2c-4f3d-8e4f-5a6b7c8d9e0a
Content-Type: application/json
{
"code": "ENT001-UPD",
"name": "Updated Entity",
"remark": "Updated"
}
Delete Entity
DELETE /api/app/my-entity-name/7d8e5d1a-1b2c-4f3d-8e4f-5a6b7c8d9e0a
Note: The actual route prefix may be affected by module configuration, refer to
MyEntityNameControllerdefinition.
Section sources