Foreign key breach error only in inclusion via API, via insertion bank is correct

Asked

Viewed 200 times

0

I have a . NET Core API that connects to a Postgres database using Entity Framework.

For each table that needs to do some insertion I have the model with the right fields (created by hand because I had problem with scaffold).

And the table that’s generating me the problem is called tbattributes, in it I have a field called tbaaditivos_idaditive referenced with the table tbadditive in the field idaditive.

Before I had created without defining whether to accept null or not, however, after the first error, excludes the field and FK and recreated as follows.

ALTER TABLE tbatributo ADD COLUMN tbaditivo_idtbaditivo INTEGER NULL;
ALTER TABLE tbatributo
ADD FOREIGN KEY (tbaditivo_idtbaditivo) 
REFERENCES public.tbaditivo(idtbaditivo)

Done this it was possible to create records via bank without the idtbadditive field as can be seen in the following image: comando de inserção na tabela tbatributos definindo tbaditivo_idtbaditivo como null executando corretamente via pgadmin

However, the error in inserting via api remains.

I don’t have Migrations or anything because I didn’t use scaffold-dbcontext or add-Migrations.

When I tested deleting the key, the error disappeared and the insertion occurred correctly, however, that’s not what I want.

Imagem do erro PostgresException: 23503: insert or update on table tbatributo violates foreign key constraint tbatributo_tbaditivo_idtbaditivo_fkey aparecendo na tela do visual studio na linha _context.saveChanges"

Create from table tbattribute

CREATE TABLE public.tbatributo
(
    idtbatributo integer NOT NULL DEFAULT nextval('tbatributo_idtbatributo_seq'::regclass),
    valortbatributo character varying(45) COLLATE pg_catalog."default",
    datatbatributo character varying(45) COLLATE pg_catalog."default",
    tbsituacao_idtbsituacao integer NOT NULL,
    tbcampo_idtbcampo integer NOT NULL,
    tbcontrato_idtbcontrato integer NOT NULL,
    tbaditivo_idtbaditivo integer,
    CONSTRAINT tbatributo_pkey PRIMARY KEY (idtbatributo),
    CONSTRAINT tbatributo_tbaditivo_idtbaditivo_fkey FOREIGN KEY (tbaditivo_idtbaditivo)
        REFERENCES public.tbaditivo (idtbaditivo) MATCH SIMPLE
        ON UPDATE NO ACTION
        ON DELETE NO ACTION,
    CONSTRAINT tbatributo_tbcontrato_idtbcontrato_fkey FOREIGN KEY (tbcontrato_idtbcontrato)
        REFERENCES public.tbcontrato (idcontrato) MATCH SIMPLE
        ON UPDATE NO ACTION
        ON DELETE NO ACTION
)
WITH (
    OIDS = FALSE
)
TABLESPACE pg_default;

ALTER TABLE public.tbatributo
    OWNER to postgres;

My tbattribute class in api:

 public class tbatributo : BaseClass
{
    [Key]
    public int idtbatributo { get; set; }
    public string valortbatributo { get; set; }
    public string datatbatributo { get; set; }
    public int tbsituacao_idtbsituacao { get; set; }
    public int tbcampo_idtbcampo { get; set; }
    public int tbcontrato_idtbcontrato { get; set; }
    public int tbaditivo_idtbaditivo { get; set; }
}

In the controller:

  [EnableCors]
    [HttpPost("InsereCampos")]
    public IEnumerable<tbatributo> InsereCampos()
    {
        List<tbatributo> _atributos = new List<tbatributo>();
        List<tbatributo> atributos = new List<tbatributo>();
    string body;
    using (var reader = new StreamReader(Request.Body))
    {
        body = reader.ReadToEnd();
    }
    _atributos = JsonConvert.DeserializeObject<List<tbatributo>>(body);
    foreach (tbatributo item in _atributos)
    {
        atributos.Add(_repositorio.Add(item));
    }
    return (atributos);
}

In the repository:

   [EnableCors]
    public T Add(T entidade)
    { 
        entidades.Add(entidade);

    _contexto.SaveChanges();
    return entidade;
}

Here are the files of repository, startup.Cs, program.Cs and the tbattribute controller

1 answer

1


The problem is in your model. tbaditivo_idtbaditivo is an INTEGER and therefore the default value is 0 (zero). Since there is no entry with id = 0, you receive this error from the database. Change tbaditivo_idtbaditivo to nullable and it will be possible to insert a tbatributo without tbaditivo_idtbaditivo.

Then change your model to public int? tbaditivo_idtbaditivo { get; set; }. Note the ? next to the type of property.

Browser other questions tagged

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