Schritte zum Entfernen eines Fremdschlüsseleintrags
P粉845862826
P粉845862826 2024-04-04 14:15:44
0
1
360

Ich habe zwei Tabellen EmployeeAddressEmployee 是我的主表,Address 是通过外键 AddressIdEmployee zugehörige Untertabellen.

Wenn ich lösche Employee 记录时,来自 Address, wird der Datensatz nicht gelöscht. Wie kann ich meinen Code dazu umschreiben?

Employee:
  [Id](Primary Key)
  [FirstName] 
  [LastName]
  [Email]
  [AddressId] (Foreign Key -> Address.Id)
  [Code]

Address:
  [Id] (Primary Key)
  [Details]
  [State]
  [Country]

Das ist mein aktueller Code:

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粉845862826
P粉845862826

Antworte allen(1)
P粉558478150

您正在寻找 ON DELETE CASCADE 功能,该功能将向 MySQL 指示当删除其“父”记录(在另一个表中)时应删除该记录。

类似这样的事情:

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
);
Beliebte Tutorials
Mehr>
Neueste Downloads
Mehr>
Web-Effekte
Quellcode der Website
Website-Materialien
Frontend-Vorlage
Über uns Haftungsausschluss Sitemap
Chinesische PHP-Website:Online-PHP-Schulung für das Gemeinwohl,Helfen Sie PHP-Lernenden, sich schnell weiterzuentwickeln!