Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Input validation error foreign key fields

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

"type": "https://tools.ietf.org/html/rfc9110#section-15.5.1&quot;,
"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?

>Solution :

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

  public User? FromUser { get; set; }
  public User? ToUser { get; set; }
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading