Is it possible for an entity to have 2 N-to-N relationships using Entity Framework?

Asked

Viewed 39 times

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 and Empresas shouldn’t be virtual in Endereço ? When you refer to a POST do you not mean a GET? How are you getting?

  • I wasn’t really clear, I was referring to JSON generated in the documentation of Swagger, which does not look like I would like to do a POST. And as to be virtual, I don’t know much about it yet, but I’ll study about it. Thank you for the comment.

  • 1

    As to the swagger ideal is that your API layer works with ViewModels or DTOs so much for the Requests as for the Responses, so you write these objects only with the necessary properties and that you want to expose.

No answers

Browser other questions tagged

You are not signed in. Login or sign up in order to post.