Good afternoon.
My question is, I have 2 Edit methods in my controller - get and post.
[HttpGet]
public async Task<IActionResult> Edit(Guid id)
{
var article = await _articleService.GetArticleAsync(id);
var resultModel = _mapper.Map<ArticleDetailViewModel>(article);
return View(resultModel);
}
[HttpPost]
public async Task<IActionResult> Edit(ArticleDetailViewModel model)
{
await _articleService.UpdateArticle(_mapper.Map<ArticleDTO>(model));
return RedirectToAction("Index", "Article");
}
The Guid id of the Article comes into the Edit get method. With this id, I find the entire ArticleDTO object and use the automapper to turn it into an ArticleDetailViewModel. Next, I pass this model to the View. In the Index post method, changes to the Article are edited and saved using the UpdateArticle(ArticleDTO) method. In this method, I have to manually collect one entity from 2 entities and save it.
public async Task UpdateArticle(ArticleDTO model)
{
var entity = await _unitOfWork.Articles.GetByIdAsync(model.Id);
var articleResult = new Article()
{
Id = model.Id,
Title = model.Title,
Description = model.Description,
Body = model.Body,
CreationDate = model.CreationDate,
PositivityGrade = entity.PositivityGrade,
Comments = entity.Comments,
Source = entity.Source,
SourceId = entity.SourceId
};
_unitOfWork.Articles.Update(articleResult);
await _unitOfWork.Comit();
}
Please tell me how to avoid this, and use Automapper so as not to do it manually. Or maybe there is some other way.
CodePudding user response:
I think this might be what you want:
public async Task UpdateArticle(ArticleDTO model)
{
var entity = await _unitOfWork.Articles.GetByIdAsync(model.Id);
var articleResult = _mapper.Map(model, entity)
_unitOfWork.Articles.Update(articleResult);
await _unitOfWork.Comit();
}