Icollection in Put Webapi method

Asked

Viewed 100 times

1

I have the Put method in a Webapi Rest service

        // PUT: api/pessoas/5
        [ResponseType(typeof(void))]
        public IHttpActionResult Putpessoa(int id, pessoa pessoa)
        {
            if (!ModelState.IsValid)
            {
                return BadRequest(ModelState);
            }

            if (id != pessoa.id)
            {
                return BadRequest();
            }

            //exibição dos itens da entidade usuario
            var usuario = new usuario
            {
                id = pessoa.id,
                login = pessoa.usuario.login,
                senha = pessoa.usuario.senha,
                ativo = pessoa.usuario.ativo
            };

            db.pessoa.Add(pessoa);
            usuario.pessoa = pessoa;
            db.usuario.Add(usuario);


        db.Entry(pessoa).State = EntityState.Modified;

            try
            {
                db.SaveChanges();
            }
            catch (DbUpdateConcurrencyException)
            {
                if (!pessoaExists(id))
                {
                    return NotFound();
                }
                else
                {
                    throw;
                }
            }

            return StatusCode(HttpStatusCode.NoContent);
        }

Personal class_address

namespace WebApi.Models
{
    using System;
    using System.Collections.Generic;
    using System.ComponentModel.DataAnnotations;
    using System.ComponentModel.DataAnnotations.Schema;
    using System.Data.Entity.Spatial;
    using Newtonsoft.Json;

    [Table("pessoa_endereco")]
    public partial class pessoa_endereco
    {
        [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
        public int id { get; set; }

        public int pessoa_id { get; set; }

        [Required]
        [StringLength(100)]
        public string logradouro { get; set; }

        [StringLength(20)]
        public string numero { get; set; }

        [StringLength(50)]
        public string complemento { get; set; }

        [StringLength(50)]
        public string ponto_referencia { get; set; }

        [Required]
        [StringLength(8)]
        public string cep { get; set; }

        [StringLength(50)]
        public string bairro { get; set; }

        [StringLength(100)]
        public string nome_contato { get; set; }

        [StringLength(20)]
        public string telefone_1 { get; set; }

        [Required]
        [StringLength(10)]
        public string ramal_telefone_1 { get; set; }

        [StringLength(20)]
        public string telefone_2 { get; set; }

        [Required]
        [StringLength(10)]
        public string ramal_telefone_2 { get; set; }

        [StringLength(20)]
        public string celular { get; set; }

        [StringLength(100)]
        public string email { get; set; }

        [JsonIgnore]
        public virtual pessoa pessoa { get; set; }
    }
}

It is working, but I need to add another relationship with another entity called person_addressable, similar to the user entity relationship. The problem is that user is 1 to 1 and personal is 1 (person) to many (person).

 //relacionamento de pessoa com entidade usuario
 public virtual usuario usuario { get; set; }

 //relacionamento de pessoa com entidade pessoa_endereco
 public virtual ICollection<pessoa_endereco> pessoa_endereco { get; set; }

I tried to do the same way user but it doesn’t work:

var pessoa_endereco = new pessoa_endereco
{
      id = pessoa.id,
      logradouro = pessoa.pessoa_endereco.logradouro
};

Error appears:

Cannot implicitly convert type "System.Collections.Generic.Icollection" to "string" Webapi

But if I do:

 var pessoa_endereco = new pessoa_endereco
    {
          id = pessoa.id,
          logradouro = 'rua teste'
    };

directly writing it works. But what I need is to get the values that come from the json that was sent to that post.

I solved the problem by following the instructions of Cassio, I did not need to touch the classes (entities) only add in the controller, in the PUT and POST method the code:

var person_address1 = new person_addressee_address();

        foreach (var pessoa_endereco in pessoa.pessoa_endereco)
        {
            pessoa_id = pessoa.id;
            logradouro = pessoa_endereco.logradouro;
            cep = pessoa_endereco.cep;
            ramal_telefone_1 = pessoa_endereco.ramal_telefone_1;
            ramal_telefone_2 = pessoa_endereco.ramal_telefone_1;

            pessoa_endereco1 = pessoa_endereco;
        };

        db.pessoa.Add(pessoa);
        pessoa_endereco1.pessoa = pessoa;
        db.pessoa_endereco.Add(pessoa_endereco1);
  • And how’s the personal class?

  • @Cassioalves added the personal class_addressed in the question

1 answer

1


I think you should change your relationship to:

Person

class pessoa
{
    public pessoa() 
    {
        pessoa_endereco = new List<pessoa_endereco>();
    }

    public string codigo { get; set; }
    public string nome { get; set; }
    public ICollection<pessoa_endereco> pessoa_endereco { get; set; }
}

Personal

class pessoa_endereco
{   
    public pessoa_endereco() { }

    public string codigo { get; set; }
    public string logradouro { get; set; }
    public virtual pessoa pessoa { get; set; }

}

Main

public static void Main()
{

    var pessoa_endereco  = new pessoa_endereco(){
        codigo = "1",
        logradouro = "rua 1"
    };

    var pessoa2 = new pessoa
    {
        codigo = "2",
        nome = "cassio"
    };

    pessoa2.pessoa_endereco.Add(pessoa_endereco);


    foreach (var item in pessoa2.pessoa_endereco)
    {
        Console.WriteLine(item.logradouro);
    }
}

Dai in its Function Putpessoa you use your logic.

Example link : https://dotnetfiddle.net/CMUuYd

  • I thought that too, however, it gives a mistake when I go to consult by soapUhe error, indicating that I have to change the relationship in the bank, however, there are customers who have more than one address, changing the relationship, 1 to 1. You think there’s a way to post this relationship?

  • At this link: https://dotnetfiddle.net/CMUuYd you have an example

  • that way it still doesn’t work because I’m using codefirst with Migrations, and it complains that I have to give an update-database, only when I do it it changes the relationship in my database by putting 1 to 1

  • I modified the answer, I think it now solves your problem.

  • I did following your instructions and it worked, posted the change in my question in case anyone needs it. Thanks friend!

  • I’m glad it worked out!

Show 1 more comment

Browser other questions tagged

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