当前位置:网站首页>DDD based on ABP -- Entity creation and update
DDD based on ABP -- Entity creation and update
2022-07-24 14:41:00 【A Sheng】
This article mainly introduces the creation of entities through constructors and domain services 2 Ways of planting , The latter is mostly used in scenarios that require other business rule detection when creating entities . Finally, it introduces how to update entities in the application service layer .
One . Create entities through constructors
If Issue The aggregation root class of is :
public class Issue : AggregateRoot<Guid>
{
public Guid RepositoryId { get; private set; } // Do not modify RepositoryId, The reason is that it is not supported to put a Issue Move to another Repository below
public string Title { get; private set; } // Cannot be modified directly Title, Can pass SetTitle() modify , It is mainly to add a pair of Title Non repeatable verification
public string Text { get; set; } // Can be modified directly
public Guid? AssignedUserId { get; internal set; } // The same assembly can be modified AssignedUserId Of
// Public constructor
public Issue(Guid id, Guid repositoryId, string title, string text=null) : base(id)
{
RepositoryId = repositoryId;
Title = Check.NotNullOrWhiteSpace(title, nameof(title));
Text = text; // Can be empty or null
}
// Private constructor
private Issue() {}
// modify Title Methods
public void SetTitle(string title)
{
// Title Can't repeat
Title = Check.NotNullOrWhiteSpace(title, nameof(title));
}
// ...
}
Create a Issue The process is as follows :
public class IssueAppService : ApplicationService.IIssueAppService
{
private readonly IssueManager _issueManager; //Issue Field service
private readonly IRepository<Issue, Guid> _issueRepository; //Issue Storage
private readonly IRepository<AppUser, Guid> _userRepository; //User Storage
// Public constructor
public IssueAppService(IssueManager issueManager, IRepository<Issue, Guid> issueRepository, IRepository<AppUser, Guid> userRepository)
{
_issueManager = issueManager;
_issueRepository = issueRepository;
_userRepository = userRepository;
}
// Create by constructor Issue
public async Task<IssueDto> CreateAssync(IssueCreationDto input)
{
var issue = new Issue(GuidGenerator.Create(), input.RepositoryId, input.Title, input.Text);
}
if(input.AssigneeId.HasValue)
{
// Get assigned to Issue Of User
var user = await _userRepository.GetAsync(input.AssigneeId.Value);
// adopt Issue Service areas , take Issue Assigned to User
await _issueManager.AssignAsync(issue, user);
}
// Insert and update Issue
await _issueRepository.InsertAsync(issue);
// return IssueDto
return ObjectMapper.Map<Issue, IssueDto>(issue);
}
Two . Create entities through domain services
Under what circumstances will domain services be used to create entities , Instead of creating entities through entity constructors ? It is mainly used in scenarios that require other business rule detection when creating entities . such as , Creating Issue When , Can't create Title same Issue. adopt Issue Entity constructor to create Issue Entity , This is uncontrollable . That's why entities are created through domain services . Block from Issue Constructor to create Issue Entity , The access rights of its constructor need to be determined by public It is amended as follows internal:
public class Issue : AggregateRoot<Guid>
{
// ...
internal Issue(Guid id, Guid repositoryId, string title, string text = null) : base(id)
{
RepositoryId = repositoryId;
Title = Check.NotNullOrEmpty(title, nameof(title));
Text = text; // It is allowed to be empty or null
}
// ...
}
Through domain service IssueManager Medium CreateAsync() Method to determine the created Issue Of Title Whether to repeat :
public class IssueManager:DomainService
{
private readonly IRepository<Issue,Guid> _issueRepository; // Issue The warehouse of
// Public constructor , Injection warehousing
public IssueManager(IRepository<Issue,Guid> issueRepository)
{
_issueRepository=issueRepository;
}
public async Task<Issue> CreateAsync(Guid repositoryId, string title, string text=null)
{
// Judge Issue Of Title Whether to repeat
if(await _issueRepository.AnyAsync(i=>i.Title==title))
{
throw new BusinessException("IssueTracking:IssueWithSameTitleExists");
}
// Return to the created Issue Entity
return new Issue(GuidGenerator.Create(), repositoryId, title, text);
}
}
In the application service layer IssueAppService Pass through IssueManager.CreateAsync() Create entities as follows :
public class IssueAppService :ApplicationService.IIssueAppService
{
private readonly IssueManager _issueManager; //Issue Service areas
private readonly IRepository<Issue,Guid> _issueRepository; //Issue The warehouse of
private readonly IRepository<AppUser,Guid> _userRepository; //User The warehouse of
// Public constructor , Inject the required dependencies
public IssueAppService(IssueManager issueManager, IRepository<Issue,Guid> issueRepository, IRepository<AppUser,Guid> userRepository){
_issueManager=issueManager;
_issueRepository=issueRepository;
_userRepository=userRepository;
}
// Create a Issue
public async Task<IssueDto> CreateAsync(IssueCreationDto input)
{
// Through domain services _issueManager.CreateAsync() Create entities , Mainly to guarantee Title No repetition
var issue=await _issueManager.CreateAsync(input.RepositoryId, input.Title, input.Text);
// obtain User, And will Issue Assigned to User
if(input.AssignedUserId.HasValue)
{
var user =await _userRepository.GetAsync(input.AssignedUserId.Value);
await _issueManager.AssignToAsynce(issue,user);
}
// Insert and update database
await _issueRepository.InsertAsync(issue);
// return IssueDto
return ObjectMapper.Map<Issue,IssueDto>(issue);
}
}
// Definition Issue The creation of DTO by IssueCreationDto
public class IssueCreationDto
{
public Guid RepositoryId{get;set;}
[Required]
public string Title {get;set;}
public Guid? AssignedUserId{get;set;}
public string Text {get;set;}
}
Now there is a question: why not put Title Duplicate detection of is done in the domain service layer , This involves the problem of distinguishing between core domain logic and application logic . Clearly here Title You cannot repeat the logic that belongs to the core domain , So we put it into domain services . Why should the title duplicate detection not be ⽤ Implementation in service ? For detailed explanation, refer to [1].
3、 ... and . Update the entity
Next, the application layer IssueAppService In the to update Entity . Definition UpdateIssueDto as follows :
public class UpdateIssueDto
{
[Required]
public string Title {get;set;}
public string Text{get;set;}
public Guid? AssignedUserId{get;set;}
}
Entity update operation UpdateAsync() The method is as follows :
public class IssueAppService :ApplicationService.IIssueAppService
{
private readonly IssueManager _issueManager; //Issue Field service
private readonly IRepository<Issue,Guid> _issueRepository; //Issue Storage
private readonly IRepository<AppUser,Guid> _userRepository; //User Storage
// Public constructor , dependent
public IssueAppService(IssueManager issueManager, IRepository<Issue,Guid> issueRepository, IRepository<AppUser,Guid> userRepository){
_issueManager=issueManager;
_issueRepository=issueRepository;
_userRepository=userRepository;
}
// to update Issue
public async Task<IssueDto> UpdateAsync(Guid id, UpdateIssueDto input)
{
// from Issue Get from warehouse Issue Entity
var issue = await _issueRepository.GetAsync(id);
// Through domain services issueManager.ChangeTitleAsync() Method update Issue The title of the
await _issueManager.ChangeTitleAsync(issue,input.Title);
// obtain User, And will Issue Assigned to User
if(input.AssignedUserId.HasValue)
{
var user = await _userRepository.GetAsync(input.AssignedUserId.Value);
await _issueManager.AssignToAsync(issue, user);
}
issue.Text=input.Text;
// Update and save Issue
// Saving entity changes is the responsibility of applying service methods
await _issueRepository.UpdateAsync(issue);
// return IssueDto
return ObjectMapper.Map<Issue,IssueDto>(issue);
}
}
Need to be in IssueManager Add ChangeTitle():
public async Task ChangeTitleAsync(Issue issue,string title)
{
// Title Unchanged, return
if(issue.Title==title)
{
return;
}
// Title Repeat and throw an exception
if(await _issueRepository.AnyAsync(i=>i.Title==title))
{
throw new BusinessException("IssueTracking:IssueWithSameTitleExists");
}
// Please update it Title
issue.SetTitle(title);
}
modify Issue Class SetTitle() The access rights of the method are internal:
internal void SetTitle(string title)
{
Title=Check.NotNullOrWhiteSpace(title,nameof(title));
}
reference :
[1] be based on ABP Framework Implement domain-driven design :https://url39.ctfile.com/f/2501739-616007877-f3e258?p=2096 ( Access password : 2096)
边栏推荐
- TypeError: Cannot read property ‘make‘ of undefined
- 多数据源配置下,解决org.apache.ibatis.binding.BindingException: Invalid bound statement (not found)问题
- MySQL community download address
- Spark Learning Notes (III) -- basic knowledge of spark core
- Su Chunyuan, founder of science and technology · CEO of Guanyuan data: making business use is the key to the Bi industry to push down the wall of penetration
- Activate the newly installed Anaconda in the server
- Rasa 3.x learning series -rasa [3.2.4] - 2022-07-21 new release
- 使用 Fiddler Hook 报错:502 Fiddler - Connection Failed
- 【NLP】下一站,Embodied AI
- Bibliometrix: dig out the one worth reading from thousands of papers!
猜你喜欢

Learning and thinking about the relevant knowledge in the direction of building network security knowledge base

Strongly connected component

About the flicker problem caused by using universalimageloader to load pictures and refresh data in recyclerview

老虎口瀑布:铜梁版小壶口瀑布

Don't lose heart. The famous research on the explosive influence of Yolo and PageRank has been rejected by the CS summit

LeetCode高频题56. 合并区间,将重叠的区间合并为一个区间,包含所有区间

Under multi data source configuration, solve org.apache.ibatis.binding Bindingexception: invalid bound statement (not found) problem

Regular expression and bypass cases

Mini examination - examination system
![Rasa 3.x learning series -rasa [3.2.4] - 2022-07-21 new release](/img/1e/27f107d514ded6641410cc5a45764b.png)
Rasa 3.x learning series -rasa [3.2.4] - 2022-07-21 new release
随机推荐
股票开户之后就可以购买6%的理财产品了?
Attributeerror: module 'distutils' has no attribute' version error resolution
【机器学习】之 主成分分析PCA
基于ABP实现DDD--实体创建和更新
Kotlin class and inheritance
CAS atomic type
Automated penetration scanning tool
PCA of [machine learning]
Learning and thinking about the relevant knowledge in the direction of building network security knowledge base
【MATLAB】MATLAB画图系列二 1.元胞与数组转化 2.属性元胞 3.删除nan值 4.合并多fig为同一fig 5.合并多fig至同一axes
达梦实时主备集群搭建
Rasa 3.x 学习系列-Rasa FallbackClassifier源码学习笔记
After five years of contact with nearly 100 bosses, as a headhunter, I found that the secret of promotion was only four words
北京一卡通以35288.8529万元挂牌出让68.45%股权,溢价率为84%
Clear all spaces in the string
Data analysis and mining 1
Don't lose heart. The famous research on the explosive influence of Yolo and PageRank has been rejected by the CS summit
A common Dao class and util
TS learning record (I) sudo forgets the password (oolong) try changing the 'lib' compiler option to include 'DOM'
Rest style