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
Related
I have made a table named "reservations" which contains a customer id and a house id. I made tables for houses and customers as well. I have made a datagrid, which contains the reservations data, but I also want it to contain the customers surname and the house code.
My tables are (in SQL Server Express):
CREATE TABLE [dbo].[houses]
(
[Id] INT IDENTITY (1, 1) NOT NULL,
[Code] VARCHAR(50) NULL,
[Status] VARCHAR(50) NULL,
PRIMARY KEY CLUSTERED ([Id] ASC)
);
CREATE TABLE [dbo].[customers]
(
[Id] INT IDENTITY (1, 1) NOT NULL,
[Forename] VARCHAR(50) NULL,
[Surname] VARCHAR(50) NULL,
[Email] VARCHAR(50) NULL,
PRIMARY KEY CLUSTERED ([Id] ASC)
);
CREATE TABLE [dbo].[reservations]
(
[Id] INT IDENTITY (1, 1) NOT NULL,
[HouseId] INT NULL,
[CustomerId] INT NULL,
[StartDate] DATE NULL,
[EindDate] DATE NULL,
PRIMARY KEY CLUSTERED ([Id] ASC),
CONSTRAINT [FK_HouseId]
FOREIGN KEY ([HouseId]) REFERENCES [houses]([Id]),
CONSTRAINT [FK_CustomerId]
FOREIGN KEY ([CustomerId]) REFERENCES [customers]([Id])
);
I already created all the tables, but I don't know how to link them properly. I want to get the data and put it in a datagrid.
To select all data from Reservations, customers' Surname and house code, you need to run query:
Select R.*, C.Surname, H.Code
From [dbo].[reservations] R
inner join [dbo].[customers] C on C.Id = R.CustomerId
inner join [dbo].[houses] H on H.Id = R.HouseId
Try this:
select r.*,c.surname,h.code from reservation r,customers c,houses h where
r.customer_id=c.customer_id and r.house_id=h.house_id
I have created a junction table between two of my tables to create a many to many relationship between them.I am able to save data to them, but can't access that data again. This is written in MVC ASP.NET by the way.
My first table:
CREATE TABLE [dbo].[UserInfo] (
[Id] INT IDENTITY (1, 1) NOT NULL,
[FirstName] NVARCHAR (50) NULL,
[LastName] NVARCHAR (50) NULL,
[Email] NVARCHAR (256) NOT NULL,
[Image] VARBINARY (MAX) NULL,
[Approved] BIT NOT NULL,
[Color] NVARCHAR (10) NULL,
PRIMARY KEY CLUSTERED ([Id] ASC)
);
My second table:
CREATE TABLE [dbo].[Events] (
[Id] NVARCHAR (128) NOT NULL,
[Name] NVARCHAR (100) NOT NULL,
[StartDate] DATETIME NULL,
[EndDate] DATETIME NULL,
[Approved] BIT NOT NULL,
[room_id] INT NULL,
[color] NVARCHAR (10) NOT NULL,
[Owner] INT NULL,
PRIMARY KEY CLUSTERED ([Id] ASC),
CONSTRAINT [FK_Events_Rooms] FOREIGN KEY ([room_id]) REFERENCES [dbo].[Rooms] ([_key])
);
My junction table:
CREATE TABLE [dbo].[UserToEvent] (
[UserId] INT NOT NULL,
[EventId] NVARCHAR (128) NOT NULL,
CONSTRAINT [UserId_EventId_pk] PRIMARY KEY CLUSTERED ([UserId] ASC, [EventId] ASC),
CONSTRAINT [FK_User] FOREIGN KEY ([UserId]) REFERENCES [dbo].[UserInfo] ([Id]),
CONSTRAINT [FK_Event] FOREIGN KEY ([EventId]) REFERENCES [dbo].[Events] ([Id])
);
Code to add new relationship:
Event e = await db.Events.FindAsync(id);
string email = User.Identity.Name;
UserInfo user = db.UserInfoes.Where(x => x.Email == email).First();
user.Events.Add(e);
e.UserInfoes.Add(user);
db.Entry(user).State = EntityState.Modified;
db.Entry(e).State = EntityState.Modified;
await db.SaveChangesAsync();
Code to access relationship:
UserInfo user = await db.UserInfoes.FindAsync(id);
List<Events> events = user.Events;
I would expect events to be filled with all events associated with user, but it never has any events.
I have found a work-around which is sufficient to my needs. I added another attribute to my junction table, which then allowed me to access it within my controllers (Since there weren't only two primary keys). From here I was able to gather the data from it just like any other table. Not sure why the above method does not work however. I have used that method before without a hitch. If anyone has an answer, I would love to hear it.
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.
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).
i have problem. I need add "cascade delete on" in CONSTRAINT [FK_SumaRoute_Suma] :
CREATE TABLE [dbo].[SumaRoute] (
[Id] INT IDENTITY (1, 1) NOT NULL,
[SumaId] INT NOT NULL,
[RouteId] INT NOT NULL,
CONSTRAINT [PK_SumaRoute] PRIMARY KEY CLUSTERED ([Id] ASC),
CONSTRAINT [FK_SumaRoute_Suma] FOREIGN KEY ([SumaId]) REFERENCES [dbo].[Suma] ([Id]) ***** HERE !!! *****,
CONSTRAINT [FK_SumaRoute_Route] FOREIGN KEY ([RouteId]) REFERENCES [dbo].[Route] ([Id]) ON DELETE CASCADE
);
But SQL Server return errors:
Creating FK_Part_Suma1...
(104,1): SQL72014: .Net SqlClient Data Provider:
Msg 1785, Level 16, State 0, Line 1
Introducing FOREIGN KEY constraint 'FK_Part_Suma1' on table 'Part' may cause cycles or multiple cascade paths. Specify ON DELETE NO ACTION or ON UPDATE NO ACTION, or modify other FOREIGN KEY constraints.
(104,1): SQL72014: .Net SqlClient Data Provider:
Msg 1750, Level 16, State 0, Line 1
Could not create constraint or index. See previous errors.
An error occurred while the batch was being executed.
My tables:
CREATE TABLE [dbo].[Suma] (
[Id] INT IDENTITY (1, 1) NOT NULL,
[SumaName] NVARCHAR (50) NOT NULL,
CONSTRAINT [PK_Suma_1] PRIMARY KEY CLUSTERED ([Id] ASC)
);
CREATE TABLE [dbo].[Route] (
[Id] INT IDENTITY (1, 1) NOT NULL,
[RouteName] NVARCHAR (50) NOT NULL,
CONSTRAINT [PK_Route] PRIMARY KEY CLUSTERED ([Id] ASC)
);
EDIT: Next tables
CREATE TABLE [dbo].[Part] (
[Id] INT IDENTITY (1, 1) NOT NULL,
[PartName] NVARCHAR (50) NOT NULL,
[SumaId] INT NOT NULL,
[Place] NVARCHAR (50) NULL,
[Time] TIME (7) NULL,
CONSTRAINT [PK_Part] PRIMARY KEY CLUSTERED ([Id] ASC),
CONSTRAINT [FK_Part_Suma1] FOREIGN KEY ([SumaId]) REFERENCES [dbo].[Suma] ([Id])
);
CREATE TABLE [dbo].[Order] (
[Id] INT IDENTITY (1, 1) NOT NULL,
[PartId] INT NOT NULL,
[RouteId] INT NULL,
[SumaId] INT NOT NULL,
[DriverId] INT NULL,
[Express] BIT CONSTRAINT [DF_Order_Express] DEFAULT ((0)) NOT NULL,
[Status] INT CONSTRAINT [DF_Order_Status] DEFAULT ((0)) NOT NULL,
[TimeLeft] DATETIME NOT NULL,
[StartTransport] DATETIME NULL,
[Created] DATETIME NULL,
CONSTRAINT [PK_Order] PRIMARY KEY CLUSTERED ([Id] ASC),
CONSTRAINT [FK_Order_Part] FOREIGN KEY ([PartId]) REFERENCES [dbo].[Part] ([Id]) ON DELETE CASCADE,
CONSTRAINT [FK_Order_Route] FOREIGN KEY ([RouteId]) REFERENCES [dbo].[Route] ([Id]) ON DELETE CASCADE,
CONSTRAINT [FK_Order_Suma] FOREIGN KEY ([SumaId]) REFERENCES [dbo].[Suma] ([Id]) ON DELETE CASCADE,
CONSTRAINT [FK_Order_User] FOREIGN KEY ([DriverId]) REFERENCES [dbo].[User] ([Id]) ON DELETE CASCADE
);
CREATE TABLE [dbo].[User] (
[Id] INT IDENTITY (1, 1) NOT NULL,
[Pin] NCHAR (4) NOT NULL,
[SumaIdSigned] INT NULL,
[RouteIdSigned] INT NULL,
[Name] NVARCHAR (50) NOT NULL,
[Surname] NVARCHAR (50) NOT NULL,
[Type] BIT NOT NULL,
[TokenGCM] NVARCHAR (400) NULL,
[TokenAccess] NVARCHAR (50) NULL,
[SignedTime] DATETIME NULL,
CONSTRAINT [PK_User] PRIMARY KEY CLUSTERED ([Id] ASC),
CONSTRAINT [FK_User_Route] FOREIGN KEY ([RouteIdSigned]) REFERENCES [dbo].[Route] ([Id]),
CONSTRAINT [FK_User_Suma] FOREIGN KEY ([SumaIdSigned]) REFERENCES [dbo].[Suma] ([Id])
);
I can remove Suma, Route and User. If i remove Suma row (id = 5) and any Order contain SumaId(5) so i need remove all Orders with sumaId(5).
What i have doing pls?
Sorry my english :)