简体   繁体   中英

ASP.NET the insert statement conflicted with the foreign key constraint

I need some guidance as to why i keep getting this error for my website every time I try to add a product. To let you know I did change the database around a bit, but after I did that i completely recreated the database. I keep getting the following error:

The INSERT statement conflicted with the FOREIGN KEY constraint "FK_dbo.OrderDetails_dbo.Orders_OrderId". The conflict occurred in database "MythData.mdf", table "dbo.Orders", column 'Id'.

the two tables are OrderDetail and Orders .

Order:

CREATE TABLE [dbo].[Orders] 
(
    [Id]          INT            IDENTITY (1, 1) NOT NULL,
    [CustomerId]  INT            NOT NULL,
    [ProductId]   INT            NOT NULL,
    [ShipName]    NVARCHAR (MAX) NULL,
    [ShipAddress] NVARCHAR (MAX) NULL,
    [ShipCity]    NVARCHAR (MAX) NULL,
    [ShipState]   NVARCHAR (MAX) NULL,
    [ShipZip]     NVARCHAR (MAX) NULL,

    CONSTRAINT [PK_dbo.Orders] PRIMARY KEY CLUSTERED ([Id] ASC),
    CONSTRAINT [FK_dbo.Orders_dbo.Customers_CustomerId] 
      FOREIGN KEY ([CustomerId]) 
      REFERENCES [dbo].[Customers] ([Id]) ON DELETE CASCADE
);

CREATE NONCLUSTERED INDEX [IX_CustomerId] 
   ON [dbo].[Orders]([CustomerId] ASC); 

OrderDetail table:

CREATE TABLE [dbo].[OrderDetails] 
(
    [Id]          INT             IDENTITY (1, 1) NOT NULL,
    [OrderId]     INT             NOT NULL,
    [ProductId]   INT             NOT NULL,
    [TotalCost]   DECIMAL (18, 2) NOT NULL,
    [SubTypeMail] BIT             NOT NULL,
    [Quantity]    INT             NOT NULL,

    CONSTRAINT [PK_dbo.OrderDetails] PRIMARY KEY CLUSTERED ([Id] ASC),
    CONSTRAINT [FK_dbo.OrderDetails_dbo.Orders_OrderId] 
       FOREIGN KEY ([OrderId]) 
       REFERENCES [dbo].[Orders] ([Id]) ON DELETE CASCADE
);

CREATE NONCLUSTERED INDEX [IX_OrderId]
    ON [dbo].[OrderDetails]([OrderId] ASC);

Also the class that the error is popping up in :

using (DataContext entities = new DataContext())
{
     var orderDetail = entities.OrderDetails.Create();
     decimal price = 0;

     if (drpSub.SelectedValue == "Mailed")
     {
         price = 10;
         orderDetail.SubTypeMail = true;
     }
     else
     {
         price = 5;
         orderDetail.SubTypeMail = false;
     }

     Count = orderDetail.Quantity;
     orderDetail.TotalCost = Count * price;

     entities.OrderDetails.Add(orderDetail);
     entities.SaveChanges(); << this line is the issue!
}

Also including exactly what the trace stated:

Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: System.Data.SqlClient.SqlException: The INSERT statement conflicted with the FOREIGN KEY constraint "FK_dbo.OrderDetails_dbo.Orders_OrderId". The conflict occurred in database "MythData.mdf", table "dbo.Orders", column 'Id'.

Source Error:

Line 121: orderDetail.TotalCost = Count * price;
Line 122: entities.OrderDetails.Add(orderDetail);
Line 123: entities.SaveChanges();
Line 124: while (Count != 0)
Line 125: {

Source File: c:\\Users\\arielle davenport\\Desktop\\pets\\pets\\MythPetsDatabase\\MythPetsDatabase\\Pages\\Products.aspx.cs Line: 123

I know this is long but any help is appreciated. Really stuck right now!

The error message is telling you exactly what the problem is: You're trying to insert a row that has a foreign key constraint to another table, and the value in that column does not exist in the other table.

Let's break it down:

The INSERT statement conflicted with the FOREIGN KEY constraint "FK_dbo.OrderDetails_dbo.Orders_OrderId". 
The conflict occurred in database "MythData.mdf", table "dbo.Orders", column 'Id'.

It gives you the name of the constraint, so you can look at its definition if you need to. But the name pretty much tells you what you need to know... there's a constraint that the OrderId in the OrderDetails table has to match an Id in the Orders table. But the Orders table doesn't currently have an id that matches the one you're trying to insert into the OrderDetails table. It even tells you the problem is in the Orders Table, where the "id" column doesn't have a matching value for the row you're trying to insert into OrderDetails.

There are two potential causes:

1) There is a bug in your code which is trying to insert the wrong value into the id column in the OrderDetails table, or which is just failing to insert a row into the Order table at all

or more likely:

2) You're trying to insert rows in the wrong order... you need to insert the order into the Orders table BEFORE trying to insert the OrderDetails for that order.

You MUST make sure you have inserted the Order before you insert the OrderDetails, so that the critera of the Foreign Key Constaint is satisfied. This is precisely what FK Constraints are for: To prevent you from inserting inconsistent data, where certain values aren't valid (yet).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM