Error "cascade delete on" - c#

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 :)

Related

How do I link 3 tables using foreign keys?

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

INSERT statement conflicted with the FOREIGN KEY constraint error

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

How can I access data from my junction table?

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.

Updating a key referencing a child table gives constraint error while it shouldn't

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.

Dealing with Master data table and Related tables in Entity Framework

I have 3 tables
Employee(ID,FirstName,LastName) - in which we have all the employees including managers etc.,
EmployeeRole(RoleID,Role) - Here we defined the role of the employees
Project(ProjectName,Manager,Employee,Date..) - here the details of the projects which are assigned to all the employees.
In the project table i have columns like Emmployee,Manager, both the columns are foreign key to the Employee table. The problem is I having input like (Firstname,Lastname), how do i find the id of the emplyee.
Or are the Table Structure is wrong?
When i try to insert data in the Project Table, EmployeeRole table is also updating.It should not update the EMployeeRole Table. its a master data.
Please suggest me the solution?
Your logical data model is not correct (IMHO).
A Project can have many Employees. And a Employee can work on one or more Projects as a particular Role.
So it's a many to many between Employee and Project, with the intersection table having a Role type.
e.g.
CREATE TABLE [dbo].[Employee](
[EmployeeID] [int] NOT NULL,
[FirstName] [nvarchar](50) NOT NULL,
[LastName] [nvarchar](50) NOT NULL,
[RoleID] [int] NOT NULL,
CONSTRAINT [PK_Employee] PRIMARY KEY CLUSTERED
(
[EmployeeID] ASC
))
GO
CREATE TABLE [dbo].[Project](
[ProjectID] [int] NOT NULL,
[ProjectName] [nvarchar](50) NOT NULL,
CONSTRAINT [PK_Project] PRIMARY KEY CLUSTERED
(
[ProjectID] ASC
))
GO
CREATE TABLE [dbo].[ProjectEmployee](
[ProjectID] [int] NOT NULL,
[EmployeeID] [int] NOT NULL,
[RoleID] [int] NOT NULL,
CONSTRAINT [PK_ProjectEmployee] PRIMARY KEY CLUSTERED
(
[ProjectID] ASC,
[EmployeeID] ASC,
[RoleID] ASC
))
GO
CREATE TABLE [dbo].[Role](
[RoleID] [int] NOT NULL,
[RoleName] [int] NOT NULL,
CONSTRAINT [PK_Role] PRIMARY KEY CLUSTERED
(
[RoleID] ASC
))
GO
ALTER TABLE [dbo].[ProjectEmployee] WITH CHECK ADD CONSTRAINT [FK_ProjectEmployee_Employee] FOREIGN KEY([EmployeeID])
REFERENCES [dbo].[Employee] ([EmployeeID])
GO
ALTER TABLE [dbo].[ProjectEmployee] WITH CHECK ADD CONSTRAINT [FK_ProjectEmployee_Project] FOREIGN KEY([ProjectID])
REFERENCES [dbo].[Project] ([ProjectID])
GO
ALTER TABLE [dbo].[ProjectEmployee] WITH CHECK ADD CONSTRAINT [FK_ProjectEmployee_Role] FOREIGN KEY([RoleID])
REFERENCES [dbo].[Role] ([RoleID])
GO
Then your LinqToEntity looks like this:
// Add a new Role
Role role = new Role();
role.RoleID = 1; // TODO: make identity in database
role.RoleName = "Role 1";
db.Roles.Add(role);
db.SaveChanges();
// Add a new Employee
Employee employee = new Employee();
employee.EmployeeID = 1; // TODO: make identity in database
employee.FirstName = "Carl";
employee.LastName = "Prothman";
db.Employee.Add(employee);
db.SaveChanges();
// Add a new Project
Project project = new Project();
project.ProjectID = 1; // TODO: make identity in database
project.ProjectName = "Create new data model";
db.SaveChanges();
// Add employee to project as role1
ProjectEmployee projectEmployee = new ProjectEmployee();
projectEmployee.ProjectID = project.ProjectID;
projectEmployee.EmployeeID = employee.EmployeeID;
projectEmployee.RoleID = role.RoleID;
db.ProjectEmployees.Add(projectEmployee);
db.SaveChanges();

Categories