1
I have 2 models: Cliente
and Empresa
, which need to have registered addresses. I created another template called Endereço
to make the relationships N for N, in which it stayed this way:
public class Endereco
{
[Key]
public int Id { get; set; }
public string Cep { get; set; }
...
public ICollection<Cliente> Clientes { get; set; }
public ICollection<Empresa> Empresas {get; set;}
The models of Cliente
and Empresa
were thus left:
public class Cliente
{
[Key]
public int Id { get; set; }
public string Pessoa { get; set; }
...
public ICollection<Endereco> Enderecos{ get; set; }
public class Empresa
{
[Key]
public int Id { get; set; }
public string RegimeTributario { get; set; }
...
public ICollection<Endereco> Enderecos{ get; set; }
But when trying to make a POST
in Cliente
, the JSON
generated by the documentation of Swagger
doesn’t stay the way I’d like it to be, staying this way:
{
"id": 0,
"pessoa": "string",
"enderecos": [
{
"id": 0,
"cep": "string",
"clientes": [
null
],
"empresas": [
{
"id": 0,
"regimeTributario": "string",
"enderecos": [
null
]
}
]
}
]
}
Implementation:
public async Task<Cliente> Registro(Cliente cliente)
{
await _context.AddAsync(cliente);
await _context.SaveChangesAsync();
return cliente;
}
Controller:
public async Task<IActionResult> Registro([FromBody] Cliente cliente)
{
if (cliente != null)
{
await _clienteRep.Registro(cliente);
return Ok(cliente);
}
return BadRequest();
}
When testing in the Postman
, if I edit this JSON
and send only the necessary data, the same are persisted in the database, but there is some way to make this JSON
used in the POST
had no data from Empresa
? Or even a better way to model these relationships.
Clientes
andEmpresas
shouldn’t bevirtual
inEndereço
? When you refer to a POST do you not mean a GET? How are you getting?– Leandro Angelo
I wasn’t really clear, I was referring to
JSON
generated in the documentation ofSwagger
, which does not look like I would like to do a POST. And as to bevirtual
, I don’t know much about it yet, but I’ll study about it. Thank you for the comment.– Yan Andrey
As to the
swagger
ideal is that your API layer works withViewModels
orDTOs
so much for theRequests
as for theResponses
, so you write these objects only with the necessary properties and that you want to expose.– Leandro Angelo