Edwin
Edwin

Reputation: 35

Can't find a solution to a insert query and foreign key conflict ADO.NET C#

Here's the exception text

Instrucción INSERT en conflicto con la restricción FOREIGN KEY "FK__Pedidos__idClien__74AE54BC". El conflicto ha aparecido en la base de datos "FB4D5206F5E37B80717CE8DC9CC0F063_CTS\SISTEMA DE GESTIÓN - ESCALANDRÚN\SISTEMA DE GESTIÓN -ESCALANDRÚN\BIN\DEBUG\ESCALANDRUN.MDF", tabla "dbo.Clientes", column 'idCliente'. Se terminó la instrucción.

Tables that are involved and queries:

Pedidos(child): idPedido (PK) (Identity), idCliente (FK), FechaPedido

Clientes(parent): idCliente (PK) (Identity), other data

INSERT INTO [Pedidos] ([idCliente], [Pedido_Fecha]) VALUES (@idCliente, @Pedido_Fecha);

I'm tryin to insert data in Pedidos table and allways i get this exception.

What i know:

*It seem to be that this exception is thrown when the referenced data in parent table doesn't exists (BUT IT DOES cheked with a simple select query in sqlmanagement studio).

*That i'm pretty new to SQL and ADO.NET

What i don't understand

*Why the insert query fails?

Upvotes: 1

Views: 1536

Answers (4)

Edwin
Edwin

Reputation: 35

I've found the error: When i made the call to the method in wich i use the insert query the parameter was declared as Int64 (Long in SQL) i gave to it an Int so the problem was that i missed a cast. Ergo the idCliente will never appear because i've been giving the query a non existant IdCliente as all of you figured out.

Upvotes: 0

Gustavo F
Gustavo F

Reputation: 2206

Make sure you have the idCliente in the table Clientes with the same Id that are you inserting in Pedidos.

Upvotes: 0

Phil Sandler
Phil Sandler

Reputation: 28016

If you are sure that the data exists in Clientes, go back and check to make sure everything else is expected.

For example, verify that the value of @idCliente is as expected. Verify that this INSERT statement is happening when are where you think it is, etc.

Upvotes: 0

user596075
user596075

Reputation:

What is happening is that you are attempting to put a value in Pedidos, column idCliente that doesn't exist in Clientes, column idCliente.

Here's an example of what you're doing wrong:

dbo.Clientes

idCliente    other data
1            ....
2            ....
3            ....

dbo.Pedidos

idPedido    idCliente    other data
1           1            ....
2           1            ....
3           2            ....
4           2            ....

Now, that is all well and relational. But if you were to do this:

insert into dbo.Pedidos(idCliente)
values(4)
go

You would get an error. This is because Clientes doesn't contain an idCliente with a value of 4. It's all about relational integrity. A foreign key constraint will not let you just put any value in there. It must match up with the what it represents.

Upvotes: 2

Related Questions