PK and FK Conflict in SQL Server Database

Asked

Viewed 589 times

0

I am facing a Primary Key and Foreign Key conflict problem in SQL Server 2017 Express. I am using ASP.NET with Entity Framework Code First (Migrations). The problem is that when I add a new Client that is a Person does not add. The Entity Framework even creates the tables with the relationship, puts primary key in the two tables, also places the Clienteid as FK in the Client table, but does not insert in the database.

Error occurred:

Sqlexception: The INSERT statement conflicted with the FOREIGN KEY constraint "Fk_cliente_person". The conflict occurred in the database "Testetecnicodb", table "dbo.Pessoa", column 'Pessoaid'. The instruction has been completed.

Client class:

public class Cliente
{
    [Key]
    [ForeignKey("Pessoa")]
    public int ClienteId { get; set; }
    public virtual Pessoa Pessoa { get; set; }

    public Cliente()
    {
        Pessoa pessoa = new Pessoa();
        ClienteId = pessoa.PessoaId;
    }
}

Class Client Configuration

public class ClienteConfiguration : EntityTypeConfiguration<Cliente>
{
    public ClienteConfiguration()
    {
        HasKey(c => c.ClienteId);
    }
}

Classe Pessoa

public class Pessoa
{
    public int PessoaId { get; set; }
    public TipoPessoa TipoPessoa { get; set; }

    public virtual Cliente Cliente { get; set; }
    public virtual PessoaFisica PessoaFisica { get; set; }
    public virtual PessoaJuridica PessoaJuridica { get; set; }
    public IEnumerable<Endereco> Enderecos { get; set; }
}

Class Person Configuration

public class PessoaConfiguration : EntityTypeConfiguration<Pessoa>
{
    public PessoaConfiguration()
    {
        HasKey(p => p.PessoaId);
    }
}

Tables in the Bank:

Mapeamento no Banco de Dados

Does anyone know how this problem can be solved?

  • the way it seems you are trying to insert in Person an Id that does not yet exist in customer

  • @Lucas Miranda The idea is to insert a Person and take the person’s ID and insert it into the Client Table and the Physical Person Table if the client is a natural person. I was able to do Stored Procedures, but I can’t send the Views data to the database.

No answers

Browser other questions tagged

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