skip to Main Content

I have a class MessageModel, which has a field
public string? AttachedFile

My controller adds a message to the database

[SwaggerOperation(Summary = "Create Message")]        
public async Task<IActionResult> AddMessage(MessageModel messageModel)
{
    if (messageModel.AttachedFile != null)
    {
        var mediaDto = _mapper.Map<MediaDto>(messageModel);
        var createdMedia = await _mediaService.Create(mediaDto);

        messageModel.SetMediaGuid(createdMedia);
    }
    return Ok(await _messageService.Create(_mapper.Map<MessageDto>(messageModel)));
} 

My other controller edits the message, but i don’t want to update AttachedFile field when editing my existing message

[HttpPost]
[SwaggerOperation(Summary = "Edit Message")]

public async Task<IActionResult> EditMessage(MessageModel messageModel)
{
    await _messageService.Update(messageModel.Id, _mapper.Map<MessageDto>(messageModel));
    return Ok();
}

How do i ignore AttachedFile field when using Edit Message Controller

2

Answers


  1. Possibly the easiest option would be to just use 2 separate models (possibly with some base one to contain base/shared props):

    public abstract class MessageModelBase
    {
       // ...
    }
    
    public class AddMessageModel : MessageModelBase
    {
       public ... AttachedFile {get; set;}
    }
    
    public class EditMessageModel : MessageModelBase
    {
    }
    

    And use them:

    [SwaggerOperation(Summary = "Create Message")]        
    public async Task<IActionResult> AddMessage(AddMessageModel messageModel)
    {
        // ...
    } 
    
    [SwaggerOperation(Summary = "Edit Message")]
    public async Task<IActionResult> EditMessage(EditMessageModel messageModel)
    {
        // ...
    }
    

    Also possibly EditMessage should be PUT, not POST.

    Login or Signup to reply.
  2. Either you go with the answer provided above from Guru, or you make an adjustment in your repository method messageRepository.Update(entity), which will only update the fields you want to update.

    Something like this, given you’re using entity framework.

       public void UpdateEntity(MessageModel message)
        {
            // Retrieve the existing entity
            var existingEntity = _dbContext.GetEntityById(message.id);
    
            if (existingEntity != null)
            {
                // Modify only the fields you want to update
                existingEntity.SomeField = newFieldData;
    
                // Save changes to the database
                _dbContext.SaveChanges();
            }
            // Handle the case where the entity is not found
        }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search