0
namespace App.Models
{
    public class User 
    {
        public int Id { get; set; }
        public string Email { get; set; }
        public string Password { get; set; }
        public string Firstname { get; set; }

        public string Lastname { get; set; }

        public ICollection<Message> SentMessages { get; set; }
        public ICollection<Message> ReceivedMessages { get; set; }
    }
}

namespace App.Models
{
    public class Message 
    {
        public int Id { get; set; }
        public string Content { get; set; }
        public DateTime CreatedAt {get; set;}

        public int FromUserId { get; set;}
        public int ToUserId { get; set; }

        public User FromUser { get; set; }
        public User ToUser { get; set; }
    }
}

MessageController.cs:

public async Task<IActionResult> CreateMessage(Message message)
{
    _context.Messages.Add(message);
    await _context.SaveChangesAsync();
    return Ok(message);
}

Request body:

{
    "Content": "Hi, how are you",
    "FromUserId": 1,
    "ToUserId": 2
}

I'm getting this error:

"type": "https://tools.ietf.org/html/rfc9110#section-15.5.1",
"title": "One or more validation errors occurred.",
"status": 400,
"errors": {
"ToUser": [
"The ToUser field is required."
],
"FromUser": [
"The FromUser field is required."
]
},
}

What is missing? Can anyone help?

5
  • The Message class contains two properties FromUser and ToUser which are not nullable --> they must be present in your JSON ! If you want to be able to specify just the FromUserId and leave out the FromUser - make the FromUser a nullable field Commented Jul 26, 2024 at 7:24
  • [AllowNull] public User FromUser { get; set; } Tried something like that, but no luck Commented Jul 26, 2024 at 7:28
  • public User? FromUser { get; set; } Commented Jul 26, 2024 at 7:33
  • Create Data Transfer Objects (DTOs) Commented Jul 26, 2024 at 8:07
  • A reccomendation here would be migrating from using the model class and into a DTO - which would avoid you having to mess with the model class. Commented Jul 26, 2024 at 8:08

1 Answer 1

3

In class Message, you need allow null field FromUser, ToUser

  public User? FromUser { get; set; }
  public User? ToUser { get; set; }
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.