I’m making a post and I’m passing an object called Employee.
This Employee object has a field idSituation, which is a foreign key to another object Situation.
When I try to make a call via post to the Login API passing the Employee type, it gives a message that says
Situation object field is required.
I wanted to pass only the Employee object and within this object the Situation type field to be null. Since I’m not going to pass this data in the JSON.
Here are
-
the codes for the Employee and Situation objects
-
Post API with the JSON sent
-
Returns
public class Funcionario
{
[Key]
public Int64 idFuncionario { get; set; }
public string descricaoFuncionario { get; set; }
public int idSituacao { get; set; }
[ForeignKey("idSituacao")]
public virtual Situacao Situacao { get; set; }
}
public class Situacao
{
[Key]
public int idSituacao { get; set; }
public string descricaoSituacao { get; set; }
}
[HttpPost("Login")]
[AllowAnonymous]
public IActionResult Login(Funcionario param)
{}
https://localhost:7296/api/account/login
{
"descricaofuncionario":"master",
"senha":"A95135782aZ!"
}
{
"type": "https://tools.ietf.org/html/rfc9110#section-15.5.1",
"title": "One or more validation errors occurred.",
"status": 400,
"errors": {
"Situacao": [
"The Situacao field is required."
]
},
"traceId": "00-2314d7f68cc1c6dadba6f08f899167a8-bd41adabd04d52fd-00"
}
{
"descricaofuncionario":"master",
"senha":"A95135782aZ!",
"situacao":{"idsituacao":13,"descricaosituacao":"ativo"}
}
If you pass it with situation data, it works.
I have another project that allows sending objects employee with null status.
2
Answers
I suggest you use a Data Transfer Object (DTO). As taken from Microsoft docs:
It will abstract away all of the relational stuff and masks your database structure.
Something like this:
And your endpoint will look like:
I’ve used separate DTOs for both the request and response types. So for example, if you need to return a Functionario object with the id (and no Situation data) then you can create a separate
FuncitonarioResponseDto
. Like this:And if your POST response returns something it could look like this:
Instead of posting the data with the entity type, we recommend working with Data Transfer Object. Data Transfer Object aims to provide a model template for transferring data between the view (front-end) and controller (back-end) with the data/property that is only required.
Next, you need to implement casting from
LoginModel
toFuncionario
withimplicit
/explicit
operator. Note that create a partial class with the same name and namespace asFuncionario
.Use the
LoginModel
as your request body type in your controller action and cast theparam
to theFuncionario
instance if required.Alternatively, you may look for AutoMapper library to perform the type casting.