Rumah > Soal Jawab > teks badan
Saya mempunyai dua jadual Employee
和 Address
。 Employee
是我的主表,Address
是通过外键 AddressId
与 Employee
subjadual berkaitan.
Apabila saya memadam Employee
记录时,来自 Address
rekod tidak akan dipadamkan. Bagaimanakah saya boleh menulis semula kod saya untuk melakukan ini?
Employee: [Id](Primary Key) [FirstName] [LastName] [Email] [AddressId] (Foreign Key -> Address.Id) [Code] Address: [Id] (Primary Key) [Details] [State] [Country]
Ini kod semasa saya:
public bool DeleteEmployee(int id) { using (var context=new EmployeeDBEntities()) { var employee = context.Employee.FirstOrDefault(x => x.Id == id); if (employee != null) { context.Employee.Remove(employee); context.SaveChanges(); return true; } return false; } }
P粉5584781502024-04-05 10:33:38
Anda sedang mencari fungsi ON DELETE CASCADE
yang akan menunjukkan kepada MySQL bahawa rekod harus dipadamkan apabila rekod "ibu bapa"nya (dalam jadual lain) dipadamkan.
Perkara seperti ini:
CREATE TABLE address ( Id INT PRIMARY KEY AUTO_INCREMENT, Details VARCHAR(255) NOT NULL, State VARCHAR(255) NOT NULL, Country VARCHAR(255) NOT NULL ); CREATE TABLE employee ( Id INT PRIMARY KEY AUTO_INCREMENT, FirstName VARCHAR(255) NOT NULL, LastName VARCHAR(255) NOT NULL, Email VARCHAR(255) NOT NULL, AddressId INT NOT NULL, Code VARCHAR(255) NOT NULL, FOREIGN KEY (AddressId) REFERENCES address (Id) ON DELETE CASCADE );