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).
Related
I have a very large CSV file I have to load on a regular basis that contains time series data. Examples of the headers are below:
| SiteName | Company | Date | ResponseTime | Clicks |
This data comes from a service external to the uploader. SiteName and Company are both string fields. In the database these are normalized. There is a Site table and a Company table:
CREATE TABLE [dbo].[Site] (
[Id] INT NOT NULL IDENTITY(1, 1) PRIMARY KEY,
[Name] NVARCHAR(MAX) NOT NULL
)
CREATE TABLE [dbo].[Company] (
[Id] INT NOT NULL IDENTITY(1, 1) PRIMARY KEY,
[Name] NVARCHAR(MAX) NOT NULL
)
As well as the data table.
CREATE TABLE [dbo].[SiteStatistics] (
[Id] INT NOT NULL IDENTITY(1, 1) PRIMARY KEY,
[CompanyId] INT NOT NULL,
[SiteId] INT NOT NULL,
[DataTime] DATETIME NOT NULL,
CONSTRAINT [SiteStatisticsToSite_FK] FOREIGN KEY ([SiteId]) REFERENCES [Site]([Id]),
CONSTRAINT [SiteStatisticsToCompany_FK] FOREIGN KEY ([CompanyId]) REFERENCES [Company]([Id])
)
At around 2 million rows in the CSV file any sort of IO-bound iteration isn't going to work. I need this done in minutes, not days.
My initial thought is that I could pre-load Site and Company into DataTables. I already have the CSV loaded into a datatable in the format that matches the CSV columns. I need to now replace every SiteName with the Id field of Site and every Company with the Id field of Company. What is the quickest, most efficient way to handle this?
If you go with Pre-Loading the Sites and Company's you can get the distinct values using code:
DataView view = new DataView(table);
DataTable distinctCompanyValues = view.ToTable(true, "Company")
DataView view = new DataView(table);
DataTable distinctSiteValues = view.ToTable(true, "Site")
Then load those two DataTables into their SQL Tables using Sql-Bulk-Copy.
Next dump all the data in:
CREATE TABLE [dbo].[SiteStatistics] (
[Id] INT NOT NULL IDENTITY(1, 1) PRIMARY KEY,
[CompanyId] INT DEFAULT 0,
[SiteId] INT DEFAULT 0,
[Company] NVARCHAR(MAX) NOT NULL,
[Site] NVARCHAR(MAX) NOT NULL,
[DataTime] DATETIME NOT NULL
)
Then do an UPDATE to set the Referential Integrity fields:
UPDATE [SiteStatistics] ss SET
[CompanyId] = (SELECT Id FROM [Company] c Where ss.[Company] = c.Name),
[SiteId] = (SELECT Id FROM [Site] s Where ss.[Site] = s.Name)
Add the Foreign Key constraints:
ALTER TABLE [SiteStatistics] ADD CONSTRAINT [SiteStatisticsToSite_FK] FOREIGN KEY ([SiteId]) REFERENCES [Site]([Id])
ALTER TABLE [SiteStatistics] ADD CONSTRAINT [SiteStatisticsToCompany_FK] FOREIGN KEY ([CompanyId]) REFERENCES [Company]([Id])
Finally delete the Site & Company name fields from SiteStatistics:
ALTER TABLE [SiteStatistics] DROP COLUMN [Company];
ALTER TABLE [SiteStatistics] DROP COLUMN [Site];
I'm getting the following error when trying to insert values in the table:
INSERT statement conflicted with the FOREIGN KEY constraint "FK_BookingCustomer_Booking". The conflict occurred in database "C:\USERS\B00711882\SOURCE\WORKSPACES\SAILAWAY\SAILAWAY FINAL\SAILAWAYV2\SAILAWAYV2\APP_DATA\SAILAWAY.MDF", table "dbo.Booking", column 'ID'. The statement has been terminated.
My insert statement:
CREATE PROCEDURE [dbo].[inserBookingCustomer]
#customerID INT,
#bookingID INT
AS
INSERT INTO BookingCustomer (CustomerID, BookingID)
VALUES (#customerID, #bookingID)
RETURN 0
Table definitions:
Booking:
CREATE TABLE [dbo].[Booking]
(
[ID] INT IDENTITY (1, 1) NOT NULL,
[CharterID] INT NOT NULL,
[TotalCost] MONEY NOT NULL,
[StartDate] DATE NOT NULL,
[EndDate] DATE NOT NULL,
[TotalDays] INT NOT NULL,
CONSTRAINT [PK_Booking]
PRIMARY KEY CLUSTERED ([ID] ASC),
CONSTRAINT [FK_Booking_CharterID]
FOREIGN KEY ([CharterID]) REFERENCES [dbo].[Charter] ([ID])
);
BookingCustomer (where information should be inserted):
CREATE TABLE [dbo].[BookingCustomer]
(
[ID] INT IDENTITY (1, 1) NOT NULL,
[BookingID] INT NOT NULL,
[CustomerID] INT NOT NULL,
CONSTRAINT [PK_BookingCustomer]
PRIMARY KEY CLUSTERED ([ID] ASC),
CONSTRAINT [FK_BookingCustomer_Booking]
FOREIGN KEY ([BookingID]) REFERENCES [dbo].[Booking] ([ID]),
CONSTRAINT [FK_BookingCustomer_Customer]
FOREIGN KEY ([CustomerID]) REFERENCES [dbo].[Customer] ([CustomerID])
);
This is an ASP.Net application.
Edit: My c# code: https://pastebin.com/5a8seRh4
That is because you was tried to insert a value that no are inserted before in the Booking table.
You need to insert the book first and next insert the reference of the book with the customer
I am developing a C# application with .net version 4.5.2 and an Oracle DB.
The problem I have is that I can't get Entity Framework configured right to the database. The database contains a unique keys over 4 columns, but 2 of them are nullable.
[Key, Column("GEBRUIKER", Order = 0)]
public string User { get; set; }
[Key, Column("EL1", Order = 1)]
public string Element1 { get; set; }
[Key, Column("EL2", Order = 2)]
public short? Element2 { get; set; }
[Key, Column("EL3", Order = 3)]
public short? Element3 { get; set; }
When I try to get the values through this code from the database I get a null reference exception, because element 2 or 3 is empty.
When I remove the Keys from element 2 and 3, I wont get the right data, because when element 1 is the same at 2 rows, the second row will cache element 2 and 3.
Question: How can I handle these nullable unique keys?
Added extra information:
Well, this is a part of the create script of the database:
CREATE TABLE USERS
(
GEBRUIKER VARCHAR2(3 BYTE) NOT NULL,
EL1 VARCHAR2(6 BYTE) NOT NULL,
EL2 NUMBER,
EL3 NUMBER
)
CREATE UNIQUE INDEX USERS_UK ON USERS
(GEBRUIKER, EL1, EL2, EL3)
ALTER TABLE USERS ADD (
CONSTRAINT USERS_UK
UNIQUE (GEBRUIKER, EL1, EL2, EL3)
USING INDEX USERS_UK
ENABLE VALIDATE);
It is not possible to make any changes to the structure or data, because there are multiple applications who use this database. Also there are already EL2 and EL3 rows with the value 0.
Example data:
{'USER1','A','A','C'}
{'USER1','A','B','B'}
{'USER1','B','A','C'}
When I do a linq query to select USER1 AND EL1 = A I will get the next result:
{'USER1','A','A','C'}
{'USER1','A','A','C'}
instead of:
{'USER1','A','A','C'}
{'USER1','A','B','B'}
No, you can not do that:
Look to your table creation SQL:
CREATE TABLE [dbo].[Users](
[GEBRUIKER] [nvarchar](128) NOT NULL,
[EL1] [nvarchar](128) NOT NULL,
[EL2] [smallint] NOT NULL,
[EL3] [smallint] NOT NULL,
CONSTRAINT [PK_dbo.Users] PRIMARY KEY CLUSTERED
(
[GEBRUIKER] ASC,
[EL1] ASC,
[EL2] ASC,
[EL3] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
All primary keys are Not Null!!!!
let say you want to hack this key and change it by your self with SQL then you have to send the following script which will changes the key from nun nullable to nullabe!
usersDatabaseContext.Database.ExecuteSqlCommand(#"
while(exists(select 1 from INFORMATION_SCHEMA.TABLE_CONSTRAINTS where CONSTRAINT_TYPE='FOREIGN KEY'))
begin
declare #sql nvarchar(2000)
SELECT TOP 1 #sql=('ALTER TABLE ' + TABLE_SCHEMA + '.[TableName] DROP CONSTRAINT [' + CONSTRAINT_NAME + ']')
FROM information_schema.table_constraints
WHERE CONSTRAINT_TYPE = 'FOREIGN KEY'
exec (#sql)
end
ALTER TABLE Users DROP CONSTRAINT [PK_dbo.Users]
ALTER TABLE Users ALTER COLUMN EL2 SMALLINT NULL
ALTER TABLE Users
ADD CONSTRAINT [PK_dbo.Users] PRIMARY KEY CLUSTERED ( [GEBRUIKER] ASC, [EL1] ASC, [EL2] ASC, [EL3] ASC )",
TransactionalBehavior.DoNotEnsureTransaction);
var user1 = new User { UserName = "Bassam", Element1 = "1", Element2 = null, Element3 = 3 };
I have :
- Removed all foreign keys which are related to this table
- Dropped the primary key
- Changed the **Column E2 to nullable**
- Adding the modified primary key again
This will causes an error in SQL Server / Oracle DB with the following message in case of SQL Server:
Cannot define PRIMARY KEY constraint on nullable column in table 'Users'.
Think good about it even let say you can do that what will happend with your primary key:
How can you guarantee the uniqueness of your PRIMARY key? Let say your User entity will creates the following row:
Id1 Id2 Id3 , Id4
"a" , "a" , null , null
You cannot create the same entry again because this row will be exists in the table!
I use MySql and I have 2 related tables.
The 'artikel' child table contains 3 rows each with an'idArtikel' of 1, 2 and 3.
And the 'artikelen' parent table has a row with idArtikel = 2.
If I change the idArtikel in that row to 3 (and Update()), I get an error, stating:
Update failed..exception Cannot delete or update a parent row: a
foreign key constraint fails (mydb.artikel, CONSTRAINT
fk_artikel_artikelen FOREIGN KEY (idArtikel) REFERENCES
artikelen (idArtikel) ON DELETE NO ACTION ON UPDATE NO ACTION)
All the keys are there, but i don't see the problem?!
HERE ARE THE 2 TABLE CREATION SQL scripts:
CREATE TABLE IF NOT EXISTS `mydb`.`artikelen` (
`idArtikelen` INT NOT NULL AUTO_INCREMENT,
`idKlanten` INT NOT NULL,
`idOmzetGroepen` INT NOT NULL,
`idArtikel` INT NOT NULL,
`Aantal` INT NULL,
`Omschrijving` VARCHAR(45) NULL,
`Datum` DATETIME NULL DEFAULT CURRENT_TIMESTAMP,
`StuksPrijsEx` DECIMAL(10,2) NULL,
`BtwPerc` INT NULL,
`Gefactureerd` TINYINT(1) NULL,
PRIMARY KEY (`idArtikelen`),
INDEX `idKlanten.idx` (`idKlanten` ASC),
INDEX `idArtikel.idx` (`idArtikel` ASC),
INDEX `idOmzetGroepen.idx` (`idOmzetGroepen` ASC),
INDEX `idArtikelen.idx` (`idArtikelen` ASC),
CONSTRAINT `fk_artikelen_klanten1`
FOREIGN KEY (`idKlanten`)
REFERENCES `mydb`.`klanten` (`idKlanten`)
ON DELETE NO ACTION
ON UPDATE NO ACTION)
ENGINE = InnoDB
CREATE TABLE IF NOT EXISTS `mydb`.`artikel` (
`idArtikel` INT NOT NULL AUTO_INCREMENT,
`Omschrijving` VARCHAR(35) NULL,
`Merk` VARCHAR(20) NULL,
`Type` VARCHAR(15) NULL,
`StuksPrijsEx` DECIMAL(10,2) NULL,
`idOmzetGroepen` INT NOT NULL,
`BtwPerc` INT NULL DEFAULT 21,
INDEX `idOmzetGroepen.idx` (`idOmzetGroepen` ASC),
INDEX `idArtikel.idx` (`idArtikel` ASC),
CONSTRAINT `fk_artikel_artikelen`
FOREIGN KEY (`idArtikel`)
REFERENCES `mydb`.`artikelen` (`idArtikel`)
ON DELETE NO ACTION
ON UPDATE NO ACTION,
ENGINE = InnoDB
#
Any help, is appreciated a lot!
Thanks in advance for any input.
Ron.
The error I get is this "The INSERT statement conflicted with the FOREIGN KEY constraint "FK_vacation_users". The conflict occurred in database "TestAtt", table "dbo.users", column 'userID'."
I'm trying to insert into users with this:
INSERT into users (firstName, lastName, userName, password, team, fingerID, type, isActive) VALUES ('{0}', '{1}', '{2}', '{3}', '{4}', '{5}', '{6}', '{7}')",
firstNameAddBox.Text, lastNameAddBox.Text, userNameAddBox.Text, passwordAddBox.Text,
teamAddUserCombo.Text, fingerIdAddBox.Text, userTypeAddCombo.SelectedValue, isActiveCheck.Checked);
My users table looks like this:
CREATE TABLE
users
(
userID INT NOT NULL IDENTITY,
userName NVARCHAR(50) COLLATE Romanian_CI_AS NOT NULL,
password NVARCHAR(100) COLLATE Romanian_CI_AS NOT NULL,
firstName NVARCHAR(50) COLLATE Romanian_CI_AS NOT NULL,
lastName NVARCHAR(50) COLLATE Romanian_CI_AS NOT NULL,
team TINYINT NOT NULL,
type TINYINT NOT NULL,
fingerID SMALLINT NOT NULL,
isActive BIT DEFAULT 1 NOT NULL,
CONSTRAINT PK_users PRIMARY KEY (userID),
CONSTRAINT FK_users_userType FOREIGN KEY (type) REFERENCES userType (typeID),
CONSTRAINT users_idx UNIQUE (fingerID)
);
The vacation table looks like this:
CREATE TABLE
vacation
(
ID INT NOT NULL IDENTITY,
userID INT NOT NULL,
vacation TINYINT DEFAULT 0 NOT NULL,
extraDays TINYINT DEFAULT 0 NOT NULL,
PRIMARY KEY (ID),
CONSTRAINT FK_vacation_users FOREIGN KEY (ID) REFERENCES users (userID)
);
And this is the trigger:
ALTER TRIGGER "dbo"."newUserTrigger"
on "dbo"."users"
AFTER INSERT
as
begin
DECLARE #newUserID int
SELECT #newUserID = (SELECT userID FROM Inserted)
INSERT INTO vacation (userID) VALUES (#newUserID)
end;
So if I disable the trigger the insert works but with the trigger on it seems it wont insert the userID in the vacation table also.
I think your foreign key is incorrect, the column that's referencing users is userID, not ID:
CONSTRAINT FK_vacation_users FOREIGN KEY (userID) REFERENCES users (userID)
But your trigger is also broken because inserted can contain multiple (or no) rows. So it should be:
ALTER TRIGGER "dbo"."newUserTrigger"
on "dbo"."users"
AFTER INSERT
as
begin
INSERT INTO vacation (userID) SELECT userID from Inserted
end;
Here's the problem:
CONSTRAINT FK_vacation_users FOREIGN KEY (ID) REFERENCES users (userID)
This is saying that the ID column in vacation must have a matching value in userId in users. I think (ID) should be (userID). It should work OK then.
CONSTRAINT FK_vacation_users FOREIGN KEY (ID) REFERENCES users (userID)
should be
CONSTRAINT FK_vacation_users FOREIGN KEY (userID) REFERENCES users (ID)